diff --git a/submissions_extracted/296/Q2.ipynb b/submissions_extracted/296/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3867e438d39080dc553a569d047882f111fbf8ff --- /dev/null +++ b/submissions_extracted/296/Q2.ipynb @@ -0,0 +1,441 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0) # this was to fix the shape but view wont work because the view corupts the images\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " 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", + "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)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\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", + "\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", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3*36*36\n", + "\n", + "\n", + "hidden_dim = 30\n", + "\n", + "# regretion\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", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.0009\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = 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", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss= validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# the loss is not interpretabel since i am using MSE loss you didnt have the sentax for the MAE loss so i had to use MSE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "#images, labels = next(iter(test_loader))\n", + "\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", + " #outputs = model(images[i].permute(1, 2, 0))\n", + " #probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " #predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " #img = images[i].permute(1, 2, 0) # this was to fix the shape but view wont work because the view corupts the images\n", + "\n", + " #plt.imshow(img)\n", + " #plt.title(f\"Label: {labels[i].item()}\" + f\"vs pred: {predicted}\")\n", + " #plt.axis('off')\n", + "\n", + "#plt.tight_layout()\n", + "#plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/296/Q3.ipynb b/submissions_extracted/296/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a29e65b47fd2ba97dfb1f9cf522f04cead470736 --- /dev/null +++ b/submissions_extracted/296/Q3.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import StratifiedKFold\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", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "Q3_data = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "categorical_cols = Q3_data.select_dtypes(include=[\"object\"]).columns\n", + "num_cols = Q3_data.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " Q3_data[col] = Q3_data[col].fillna(Q3_data[col].mode()[0])\n", + "for col in num_cols:\n", + " Q3_data[col] = Q3_data[col].fillna(Q3_data[col].mean())\n", + "\n", + "\n", + "Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(Q3_data)\n", + "Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#there is no categorical columns but i wrote the code just in case\n", + "print(categorical_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#in comment because we dont need it\n", + "#for col in categorical_cols:\n", + "\n", + " #le = LabelEncoder()\n", + " #Q3_data[col] = le.fit_transform(Q3_data[col].astype(str))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# no scaling for my target\n", + "features_cols = Q3_data.select_dtypes(include=[\"int64\", \"float64\", \"object\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "Q3_data[features_cols] = scaler.fit_transform(Q3_data[features_cols])\n", + "\n", + "Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "Q3_data[\"Target\"].hist()\n", + "# it is clearly inbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = Q3_data[features_cols]\n", + "y = Q3_data[\"Target\"]\n", + "\n", + "X.info()\n" + ], + "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", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=20,\n", + " max_depth=4)\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", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + " # showing class distribution\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" F1: {np.mean(lr_f1):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "# to get the feature at the top since the graghp dosnt show it\n", + "print(feature_importance[\"feature\"][0])\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[\"feature\"][0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_new = X[\"P_2\"]\n", + "# Task 2,3,4,5: Write your code here:\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=20,\n", + " max_depth=4)\n", + "\n", + " # use the singel feature only but same y\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X_new, y), start=1):\n", + " # indexing for each fold\n", + " X_train_new, X_test_new = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train_new, y_test_new = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model.fit(X_train_new, y_train_new)\n", + " y_pred_new = model.predict(X_test_new)\n", + "\n", + " accuracy = accuracy_score(y_test_new, y_pred_new)\n", + " f1 = f1_score(y_test_new, y_pred_new, zero_division=0)\n", + "\n", + "\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + "\n", + "\n", + "\n", + "print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" F1: {np.mean(lr_f1):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# with all features Accuracy: 0.8363\n", + "# F1: 0.6827\n", + "# as you can see we got same acc and F1 score even with using 1 featuer only" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/297/Q1.ipynb b/submissions_extracted/297/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fc22219a549f172dce801da476115c1caedf23bb --- /dev/null +++ b/submissions_extracted/297/Q1.ipynb @@ -0,0 +1,310 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import matplotlib.pyplot as plt\n", + "\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", + "\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(path + \"/Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "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": [ + "plt.hist(df[\"Delivery_Time\"], bins=20)\n", + "plt.xlabel(\"Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Delivery Time Distribution\")\n", + "plt.show()" + ], + "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": [ + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y = df[\"Delivery_Time\"]\n", + "\n", + "if y.nunique() <= 10:\n", + " counts = y.value_counts()\n", + " ratio = counts.min() / counts.max()\n", + "\n", + " print(\"Classification target\")\n", + " print(\"Class counts:\\n\", counts)\n", + " print(\"Imbalance ratio:\", round(ratio, 2))\n", + "else:\n", + " print(\"Regression target\")\n", + " print(y.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: CV split + Train RandomForest + Evaluate using MAE + Print average MAE\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "if y.nunique() <= 10:\n", + " cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X, y)\n", + "else:\n", + " cv = KFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in splits:\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 = RandomForestRegressor(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(\"MAE scores per fold:\", np.round(mae_scores, 3))\n", + "print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# Train a final model on the entire dataset X and y\n", + "# This model variable will then be used for feature importance\n", + "model = RandomForestRegressor(random_state=42)\n", + "model.fit(X, y)\n", + "\n", + "feature_importance = pd.Series(\n", + " model.feature_importances_, index=X.columns\n", + ").sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(8,4))\n", + "feature_importance.plot(kind=\"bar\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importance\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# Ensure model is defined if this cell is run independently\n", + "# Check if 'model' exists in global scope and is an instance of RandomForestRegressor\n", + "if 'model' not in globals() or not isinstance(globals().get('model'), RandomForestRegressor):\n", + " # If not, train a new model for this cell's execution\n", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X, y)\n", + "\n", + "y_pred = model.predict(X)\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(y_pred, bins=20)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor # Added CatBoostRegressor import\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train, X_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 = 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", + " pred_rf = rf.predict(X_test)\n", + " pred_cb = cb.predict(X_test)\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, pred_avg)\n", + " mae_scores.append(mae)\n", + " # Evaluate with MAE on averaged predictions; store per‑fold score\n", + "\n", + "print(\"MAE per fold:\", np.round(mae_scores, 3))\n", + "print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n", + "\n", + "# Report fold‑wise MAE (rounded) and the overall cross‑validated average MAE" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/297/Q2.ipynb b/submissions_extracted/297/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bf711ee40209977a3e9bd67f092304cb32aef637 --- /dev/null +++ b/submissions_extracted/297/Q2.ipynb @@ -0,0 +1,274 @@ +{ + "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, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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(\"Images batch shape:\", images_batch.shape)\n", + "print(\"Ages batch shape:\", ages_batch.shape)\n", + "#DataLoader loads the dataset in mini‑batches, which makes training faster and more memory‑efficient" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(8,4))\n", + "\n", + "for i in range(6):\n", + " img = images_batch[i].permute(1, 2, 0) # Convert from (C, H, W) to (H, W, C)\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {ages_batch[i].item()}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "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 AgeMLP(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgeMLP, self).__init__()\n", + " self.net = nn.Sequential(\n", + " nn.Linear(input_size, 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + "\n", + " for X_batch, y_batch in loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).float().view(-1, 1)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(X_batch)\n", + " loss = criterion(preds, y_batch)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).float().view(-1, 1)\n", + "\n", + " preds = model(X_batch)\n", + " loss = criterion(preds, y_batch)\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "sample_X, _ = next(iter(train_loader))\n", + "input_size = sample_X[0].numel()\n", + "\n", + "model = AgeMLP(input_size).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "\n", + "epochs = 20\n", + "for epoch in range(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}/{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.plot(train_losses, label=\"Train 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\")\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "# If the gap between train and validation curves widens, it suggests overfitting\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/297/Q3.ipynb b/submissions_extracted/297/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e7c0bd438c97aa5c13f6a14fd4adf8f80800aa86 --- /dev/null +++ b/submissions_extracted/297/Q3.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "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": [ + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "target_col = df.columns[-1]\n", + "\n", + "missing = df.isnull().sum()\n", + "print(\"Columns with missing values:\\n\", missing[missing > 0])\n", + "\n", + "num_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\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": [ + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "if len(cat_cols) > 0:\n", + " df = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "counts = y.value_counts()\n", + "ratio = counts.min() / counts.max()\n", + "print(\"Target counts:\\n\", counts)\n", + "print(\"Minority/Majority ratio:\", round(ratio, 3))\n", + "print(\"Imbalanced:\", \"Yes\" if ratio < 0.5 else \"No\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import GradientBoostingClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "# Note: Keeps class distribution in each fold.\n", + "\n", + "scores = []\n", + "use_f1 = (y.value_counts().min() / y.value_counts().max()) < 0.5\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 = GradientBoostingClassifier(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " # Note: Model is trained on each fold.\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " if use_f1:\n", + " score = f1_score(y_test, y_pred)\n", + " metric_name = \"F1\"\n", + " # Note: F1 is used when data is imbalanced.\n", + " else:\n", + " score = accuracy_score(y_test, y_pred)\n", + " metric_name = \"Accuracy\"\n", + " # Note: Accuracy is used when classes are balanced.\n", + "\n", + " scores.append(score)\n", + "\n", + "# Task 5: Print average score\n", + "print(f\"{metric_name} per fold:\", np.round(scores, 3))\n", + "print(f\"Average {metric_name}:\", round(np.mean(scores), 3))\n", + "# Note: Final score is averaged across 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/298/Q1.ipynb b/submissions_extracted/298/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f42666452f0900d82e7e49b956e53346842c5ef5 --- /dev/null +++ b/submissions_extracted/298/Q1.ipynb @@ -0,0 +1,281 @@ +{ + "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": [ + "\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", + "res_path = os.path.join(path, 'Q1_data.csv')\n", + "df_res = pd.read_csv(res_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(f\"Dataset shape: {df_res.shape}\")\n", + "df_res.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_res.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_res.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_res['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_res[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Courier_Experience_yrs', 'Delivery_Time'])\n", + "print(f\"After dropping missing : {df_clean.shape}\")\n", + "\n", + "\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\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", + "df_clean.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\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", + "\n", + "col= [\"Weather\" , \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "print('data before encoding:\\n', df_clean) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "df_clean = onehot_encoder.fit_transform(df_clean[col]) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', df_clean) #show after encoding" + ], + "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', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_clean = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #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", + "target_column = \"Delivery_Time\"\n", + "X = df_clean.drop(target_column, axis=1)\n", + "y = df_clean[target_column]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": 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/298/Q2.ipynb b/submissions_extracted/298/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6cda37eb3bfaba4d2edef5051240cb7e3e249f31 --- /dev/null +++ b/submissions_extracted/298/Q2.ipynb @@ -0,0 +1,392 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "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", + "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", + "X_train = torch.tensor(X_train , dtype=torch.float32)\n", + "X_test = torch.tensor(X_test , dtype=torch.float32)\n", + "y_train = torch.tensor(y_train , dtype=torch.float32)\n", + "y_test = torch.tensor(y_test , dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "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: {y_batch[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # 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", + " # Output layer (raw scores / logits)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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) # shape: (batch_size, 10)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\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", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36\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", + "\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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/298/Q3.ipynb b/submissions_extracted/298/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..20fbe7dea723d0fd166766fc1ce2465431242b01 --- /dev/null +++ b/submissions_extracted/298/Q3.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\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", + "res_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(res_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "def check_missing_values(df):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " # Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "for col in df:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\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", + "\n", + "for col in df:\n", + " scaler = StandardScaler()\n", + " df[col] = le.fit_transform(df[col])\n", + "\n", + "\n", + "\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", + "from sklearn.model_selection import train_test_split\n", + "\n", + "target_column = \"Target\"\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\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 KFold\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "# Calculate metrics\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "precision = precision_score(y_test, y_pred)\n", + "recall = recall_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred)\n", + "\n", + "print(\"Accuracy :\", accuracy)\n", + "print(\"Precision:\", precision)\n", + "print(\"Recall :\", recall)\n", + "print(\"F1 Score :\", f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_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/299/Q1.ipynb b/submissions_extracted/299/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d21314b307b47b545f682ca22f8b6cd90ba2e1b7 --- /dev/null +++ b/submissions_extracted/299/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd # import panadas to read file\n", + "food_path = os.path.join(path, 'Q1_data.csv') # access to file path\n", + "data = pd.read_csv(food_path) # read the file" + ], + "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", + "import matplotlib.pyplot as plt # import to visualization\n", + "plt.figure(figsize=(10, 6))\n", + "plt.scatter(data['Distance_km'],data['Preparation_Time_min'], c=data['Delivery_Time']) # use the distance an d time as factors to spread the plots\n", + "plt.colorbar(label='dleviery time')\n", + "plt.title('Geographic Distribution of delivery time')\n", + "plt.xlabel('Distance')\n", + "plt.ylabel('Preparation_Time_min')\n", + "plt.show()\n", + "\n", + "# or can just plot histogram\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(data['Delivery_Time'], bins=60, edgecolor='black')\n", + "plt.title('Distribution of Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Count')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data = data.drop(columns='Order_ID', axis=1).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# fill with mode for the object variables\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", + "# fill with mean for the float variables\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(data):\n", + " duplicates = data.duplicated().sum() # calculate the duplication\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " data.drop_duplicates(inplace=True) # handle the duplicate\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 OneHotEncoder #import OneHotEncoder [[1.0.0],[0.1.0],[0.0.1]]\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder as [0,1,2]\n", + "# Do we have categorical columns? # to encode\n", + "categorical_cols = data.select_dtypes(include=[\"object\"]).columns # check for categorical types to handle it if needed\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols)) # print the categorical columns\n", + "# we have Categorical Columns: ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "# Encode categorical columns - converts text to integers\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col].astype(str))\n", + "\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# serate features and target\n", + "from sklearn.model_selection import train_test_split #for split data in % between train and test dataset\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = data.drop(target_column, axis=1)\n", + "y = data[target_column]\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 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler as small range \"best for Linear regression , logistic regression , SVM\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train) # used fit to calculate the scale and transform to apply it\n", + "X_test_scaled = scaler.transform(X_test) #no fit here because it is test so we do not need a calculation\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#it is regression ans regression check the skewed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# sperate features and target\n", + "from sklearn.model_selection import KFold\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = data.drop(target_column, axis=1)\n", + "y = data[target_column]\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", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_absolute_error #for regression metrics\n", + "import numpy as np\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", + "# Storage for logistic regression results for each fold\n", + "mae_scores = []\n", + "\n", + "model = RandomForestRegressor()\n", + "\n", + "for train_idx, test_idx in skf.split(X_train ,X_test ):\n", + " X_train, X_test = X_train[train_idx], X_train[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n", + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics \")\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n", + "\n", + "# Print the averaged score across all folds\n", + "for x in mae_scores:\n", + " print(f\"\\n{x}:\")\n", + " print(f\" avg: {np.mean(mae_scores[x]['avg']):.4f}\")" + ], + "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': X,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted dilevery time')\n", + "plt.ylabel('Count')\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/299/Q2.ipynb b/submissions_extracted/299/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..060c3e87288f4f37203e73972055a2cf7fe195ba --- /dev/null +++ b/submissions_extracted/299/Q2.ipynb @@ -0,0 +1,413 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "\n", + "# convert 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 DataLoader, TensorDataset\n", + "\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "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", + "import matplotlib.pyplot as plt\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "plt.subplot( 2,3,1)\n", + "plt.imshow(images[1].squeeze(), cmap='gray')\n", + "plt.title(f\"Label: {labels[i].item()}\")\n", + "plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class 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", + " # bc cross entropy deal with 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,) do not use view bc it only use in binary and linear regression\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 ** to do not update the weight\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # for the same gradient\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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Device setup\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 ** can split it many hidden_dim like (hidden_dim1= 4 , hidden_dim2= 6 , hidden_dim3= 4)\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", + "# 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": [ + "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,) do not use view bc it only use in binary and linear regression\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 5: Start training for 20 epochs:\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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/299/Q3.ipynb b/submissions_extracted/299/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e0975b80ddb885bd6d77f5d37b944c9422a69fbc --- /dev/null +++ b/submissions_extracted/299/Q3.ipynb @@ -0,0 +1,312 @@ +{ + "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", + "datapath = os.path.join(path, 'Q3_data.csv')\n", + "data = pd.read_csv(datapath)" + ], + "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", + "# Analyze missing values\n", + "missing_percentage = (data.isnull().sum() / len(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": [ + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = data.isnull().sum() # importat *****\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0]) # print the column with missing values\n", + " if missing_values.any(): # if the missing values is greater than 0\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_clean = data.drop(columns= ['D_87' , 'D_88', 'B_39' , 'D_110' , 'D_111' , 'D_108' , 'B_42' , 'D_73', 'D_135' ,'D_136'] , axis =1).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check and remove duplicates if any exist\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = data_clean.duplicated().sum() # calculate the duplication\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # handle the duplicate\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(data_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Encode categorical variables if needed\n", + "# 3. Do we have categorical columns? # to encode\n", + "categorical_cols = data_clean.select_dtypes(include=[\"object\"]).columns # check for categorical types to handle it if needed\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols)) # print the categorical columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler as small range \"best for Linear regression , logistic regression , SVM\n", + "import numpy as np\n", + "\n", + "#Apply feature scaling to numerical features (Use StandardScaler)\n", + "\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "data_clean_scaled = scaler.fit_transform(data_clean) # used fit to calculate the scale and transform to apply it\n", + "\n", + "print(f\"\\nScaled ranges - Min: {data_clean_scaled.min():.2f}, Max: {data_clean_scaled.max():.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Check for target imbalance and state if it is imbalanced or not\n", + "# 1. What does our target variable (charges) look like? # check skewed\n", + "target_column = data_clean_scaled['Target']\n", + "def check_target_distribution(df, target_column):\n", + " data_clean_scaled[target_column].hist(bins=30, edgecolor='black') # hist means histogram as the figure .. bin is how many rectangles we have\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(data_clean_scaled, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# serate features and target\n", + "target_column = \"Target\"\n", + "\n", + "X = data.drop(target_column, axis=1)\n", + "y = data[target_column]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.model_selection import KFold #split data in folds and git the average of error *regression data *small dataset\n", + "from sklearn.model_selection import StratifiedKFold #important for classification problems *Ensures fair and reliable evaluation when classes are imbalanced\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score #for Classification Metrics\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", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "model[name] = {'accuracy': [], 'f1': []}\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " print(f\"Training ...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " model[name]['accuracy'].append(accuracy)\n", + " model[name]['f1'].append(f1)\n", + "\n", + "print(f\" Accuracy: {np.mean(model['accuracy']):.4f}\")\n", + "print(f\" F1-Score: {np.mean(model['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", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/3/Q1.ipynb b/submissions_extracted/3/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cadd094400be95ab346776977b6bfb42da8aa3e4 --- /dev/null +++ b/submissions_extracted/3/Q1.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "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", + "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:" + ], + "execution_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/3/Q2.ipynb b/submissions_extracted/3/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/3/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/3/Q3.ipynb b/submissions_extracted/3/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5f476844355ad8b3980dcc44c9c1e706ac10696 --- /dev/null +++ b/submissions_extracted/3/Q3.ipynb @@ -0,0 +1,185 @@ +{ + "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", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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:" + ], + "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/30/Q1.ipynb b/submissions_extracted/30/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ab93d9272a0240a8390ee31db92dc580e30420f --- /dev/null +++ b/submissions_extracted/30/Q1.ipynb @@ -0,0 +1,223 @@ +{ + "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", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)" + ], + "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' )\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", + "\n", + "\n", + "\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specif\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\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)" + ], + "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/30/Q2.ipynb b/submissions_extracted/30/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/30/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/30/Q3.ipynb b/submissions_extracted/30/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/30/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/300/Q1.ipynb b/submissions_extracted/300/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..83fedfcaa06960612c12a6f055984d109020710a --- /dev/null +++ b/submissions_extracted/300/Q1.ipynb @@ -0,0 +1,244 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "csv_file = os.path.join(path, \"Q1_data.csv\")\n", + "df=pd.read_csv(csv_file)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check(df,target_name):\n", + " df[target_name].hist(bins=30,edgecolor='black')\n", + "\n", + " plt.title(f'Distribution of {target_name}')\n", + " plt.xlabel(target_name)\n", + " plt.ylabel('Frequency')\n", + " plt.show()\n", + "\n", + "check(df,\"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_cols=[\t'Order_ID'\t,'Distance_km',\t'Preparation_Time_min\t','Courier_Experience_yrs'\t,'Delivery_Time']\n", + "df_cleans[df_col]=df[df_cols].copy\n", + "df_cleans=df_cleans.drop(\t'Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean=df.copy()\n", + "df_clean.drop(columns='Order_ID')\n", + "print(df_clean.isna().sum())\n", + "for col in[\t'Order_ID'\t,'Distance_km',\t'Preparation_Time_min\t','Courier_Experience_yrs'\t,'Delivery_Time']:\n", + " df_clean[col]=df_clean[col].fillna(df_clean[col].mean())\n", + " print(df_clean[col].isna().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean=df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder=OneHotEncoder(sparse_output=False)\n", + "data_encoded=encoder.fit_transform(df)\n" + ], + "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", + "df_scaled=scaler.fit_transform(df)\n", + "print(df_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "x=df.drop('Delivery_Time',axis=1)\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", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf=KFold(n_splits=5,shuffle=True,random_state=42)\n", + "mae_scores=[]\n", + "for foldID,(train_index,test_index) in enumerate(kf.split(x,y)):\n", + " x_train,x_test=x.iloc[train_index],x.iloc[test_index]\n", + " y_train,y_test=y.iloc[train_index],y.iloc[test_index]\n", + " model=RandomForestRegressor()\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:${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importances=pd.DataFrame({\n", + " 'feature':x.columns,\n", + " 'importance':model.feature_importances_\n", + "})\n", + "plt.figure(figsize=(10,6))\n", + "sns.barplot(x='feature',y='importance',data=feature_importances)\n", + "plt.title('Feature Importance')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred=model.predict(x)\n", + "plt.figure(figsize=(10,6))\n", + "plt.hist(y_pred,bins=30,edgecolor='black',alpha=0.7)\n", + "plt.title('Predicted Delivery Time Histogram')\n", + "plt.xlabel('Delivery Time (min)')\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/300/Q2.ipynb b/submissions_extracted/300/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ed14ec1a13425e37a237173c4db1153f65a510f0 --- /dev/null +++ b/submissions_extracted/300/Q2.ipynb @@ -0,0 +1,274 @@ +{ + "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.from_numpy(X_train)\n", + "X_test=torch.from_numpy(X_test)\n", + "y_train=torch.from_numpy(y_train)\n", + "y_test=torch.from_numpy(y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "train_dataset=TensorDataset(X_train,y_train)\n", + "test_dataset=TensorDataset(X_test,y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "train_loader=DataLoader(train_dataset,batch_size=32,shuffle=True)\n", + "test_loader=DataLoader(test_dataset,batch_size=32,shuffle=True)\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", + "print(y_batch.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images,labels=next(iter(train_loader))\n", + "plt.figure(figsize=(10,10))\n", + "for i in range(16):\n", + " plt.subplot(4,4,i+1)\n", + " plt.imshow(images[i].permute(1,2,0))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "from torch import nn\n", + "class NN4_layer(nn.Module):\n", + " def __init__(self,inputD,HiddenD,outputD):\n", + " super(NN4_layer,self).__init__()\n", + " self.l1= nn.Linear(inputD,HiddenD)\n", + " self.l2= nn.Linear(HiddenD,HiddenD)\n", + " self.l3= nn.Linear(HiddenD,HiddenD)\n", + " self.l4= nn.Linear(HiddenD,outputD)\n", + " self.relu=nn.ReLU()\n", + " def forward(self,x):\n", + " z1=self.l1(x)\n", + " a1=self.relu(z1)\n", + " z2=self.l2(a1)\n", + " a2=self.relu(z2)\n", + " z3=self.l3(a2)\n", + " a3=self.relu(z3)\n", + " outputs=self.l4(a3)\n", + " return outputs\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_loop(criterian,model,train_loader,device,optimizer):\n", + " model.train()\n", + " running_loss=0.0\n", + " for batch,(X,y) in enumerate(train_loader):\n", + " X,y=X.to(device),y.to(device)\n", + " output=model(X)\n", + " loss=criterian(output,y)\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss+=loss.item()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validation_loop(criterian,model,test_loader,device):\n", + " model.eval()\n", + " running_loss=0.0\n", + " correct=0\n", + " total=0\n", + " with torch.no_grad():\n", + " for batch,(X,y) in enumerate(test_loader):\n", + " X,y=X.to(device),y.to(device)\n", + " output=model(X)\n", + " loss=criterian(output,y)\n", + " running_loss+=loss.item()\n", + " probability=F.softmax(output,dim=1)\n", + " predicted=torch.argmax(probability,dim=1)\n", + " total+=y.size(0)\n", + " correct+=(predicted==y).sum().item()\n", + " accuracy=correct/total\n", + " return running_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=NN4_layer(3*64*64,512,1).to(device)\n", + "criterian=nn.CrossEntropyLoss()\n", + "optimizer=torch.optim.Adam(model.parameters(),lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses=[]\n", + "test_losses=[]\n", + "accuracy_list=[]\n", + "for epoch in range(20):\n", + " train_loss=train_loop(criterian,model,train_loader,device,optimizer)\n", + " test_loss,accuracy=validation_loop(criterian,model,test_loader,device)\n", + " train_losses.append(train_loss)\n", + " test_losses.append(test_loss)\n", + " accuracy_list.append(accuracy)\n", + " print(f\"Epoch {epoch+1}/{20}, Train Loss: {train_loss:.4f}, Test Loss: {test_loss:.4f}, Accuracy: {accuracy:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.plot(train_losses,label=\"train_loss\")\n", + "plt.plot(test_losses,label=\"test_loss\")\n", + "plt.legend()\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/300/Q3.ipynb b/submissions_extracted/300/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d397bda147d94925a5e6bcff41fe00a40b5bb13e --- /dev/null +++ b/submissions_extracted/300/Q3.ipynb @@ -0,0 +1,207 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.utils.text import Path\n", + "# Task 1: Write your code here:\n", + "import pandas as pd\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", + "nissing_values = df.isnull().sum()\n", + "print(nissing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()\n", + "print(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_columns = df.select_dtypes(include=['object']).columns\n", + "df = pd.get_dummies(df, columns=categorical_columns, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_columns = df.select_dtypes(include=['int64', 'float64']).columns\n", + "scaler = StandardScaler()\n", + "df[numerical_columns] = scaler.fit_transform(df[numerical_columns])\n", + "print(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_counts = df['Target'].value_counts()\n", + "print(target_counts)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features_columns = df.columns.drop('Target')\n", + "X = df[features_columns]\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold,train_test_split\n", + "from sklearn.metrics import accuracy_score,f1_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model=CatBoostClassifier(iterations=100, learning_rate=0.1, depth=6, loss_function='Logloss', random_seed=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "feature_importance = pd.DataFrame({'Feature': X.columns, 'Importance': model.feature_importances_})\n", + "feature_importance = feature_importance.sort_values(by='Importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.bar(feature_importance['Feature'], feature_importance['Importance'])\n", + "plt.xlabel('Features')\n", + "plt.ylabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.xticks(rotation=90)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = feature_importance.iloc[0]['Feature']\n", + "print(\"Golden Feature:\", golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/301/Q1.ipynb b/submissions_extracted/301/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9da5846c1dd0f647dc65a7cfdfa90dba4c350ec7 --- /dev/null +++ b/submissions_extracted/301/Q1.ipynb @@ -0,0 +1,282 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "\n", + "\n", + "from tqdm import tqdm\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_delivery = os.path.join(path, 'Q1_data.csv')\n", + "df_food_delivery = pd.read_csv(food_delivery)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food_delivery.shape}\")\n", + "df_food_delivery.head(10)\n" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food_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_clean = df_food_delivery.copy()\n", + "\n", + "df_clean = df_clean.drop(columns=['Order_ID'])\n", + "df_clean.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "\n", + "for col in ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "df_clean = onehot_encoder.fit_transform(categorical_cols.array.reshape(-1,1)) # Apply fit_transform to the copied\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "features = df_clean.Columns.drop(\"Delivery_Time\")\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #show after scaling\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = 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", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " print(f\"Training {model}...\")\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", + " print(f\" MAE: {mae}\")\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/301/Q2.ipynb b/submissions_extracted/301/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9395ca69a7947530cef3e1f987a11c5cf57fa07d --- /dev/null +++ b/submissions_extracted/301/Q2.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "# 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.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", + "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", + "from torch.utils.data import DataLoader\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\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!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/301/Q3.ipynb b/submissions_extracted/301/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..61a5d58c38510730c2a586558e12c2f13aba3855 --- /dev/null +++ b/submissions_extracted/301/Q3.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\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 = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "for col in missing_data:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "df_clean = onehot_encoder.fit_transform(categorical_cols.array.reshape(-1,1)) # Apply fit_transform to the copied\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "features = df_clean.Columns.drop(\"\")\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #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:\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": [ + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.ensemble import Cat\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score,f1_score\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " print(f\"Training {model}...\")\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", + " print(f\" MAE: {mae}\")\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/302/Q1.ipynb b/submissions_extracted/302/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c4edce102422051ad8a615a8784be67006413bdb --- /dev/null +++ b/submissions_extracted/302/Q1.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", + "from sklearn.preprocessing import StandardScaler\n", + "\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", + "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": [ + "d_path = os.path.join(path, 'Q1_data.csv') ## To Read The csv file\n", + "df_delv = pd.read_csv(d_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df_delv.shape}\")\n", + "df_delv.head() ## To print only the head of the table" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:print(f\"Shape: {df_delv.shape}\")\n", + "df_delv.info() ## To print All the info about the data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delv.describe() ## To print The info as a table" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5)) ## To graph the data we can choose any number of bins\n", + "plt.hist(df_delv['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery 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", + "\n", + "df_clean = df_delv.dropna(subset=['Order_ID']).copy() ## To clean the data and copy it to the original data\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown') ## Fill the missing data with none\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum()) ## cheake if there is any missing data stell there\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "## there is no categorical variables" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "standard_scaler = StandardScaler() ## Use the function to transfir\n", + "df_clean= standard_scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(f\"Delivery : {df_delv['Delivery_Time'].sum()}\") ## To cheak the imbalance\n", + "print(f\" Not Delivery : {(df_delv['Delivery_Time'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs'] ## but the feature in\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", + "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", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/302/Q2.ipynb b/submissions_extracted/302/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9348b30f92f644ccba145cc17fd6638c7dd109bb --- /dev/null +++ b/submissions_extracted/302/Q2.ipynb @@ -0,0 +1,335 @@ +{ + "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 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", + "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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " # 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", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + "\n", + " z4 = self.layer5(a3)\n", + "\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " 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", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = 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", + "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 = NN4Layer(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 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_one_epoch, label='Train Loss')\n", + "plt.plot(validate, 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/302/Q3.ipynb b/submissions_extracted/302/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4bce9436462d78596937fddaa2067c4b2a32520b --- /dev/null +++ b/submissions_extracted/302/Q3.ipynb @@ -0,0 +1,226 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "\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", + "\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)\n", + "\n", + "## there is no duplicate" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "## there is no categorical variables\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "standard_scaler = StandardScaler()\n", + "df= standard_scaler.fit_transform(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\" The Target: {df['Target'].sum()}\")\n", + "print(f\" Not The Target : {(df['Target'] == 0).sum()}\")" + ], + "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", + "\n", + "feature_cols = ['P_2', 'D_39','B_1', 'B_2','S_3','R_1','D_41','B_3','D_41','D_42','D_43','D_137','D_138','D_139','D_140','D_141','D_142','D_143','D_144','D_145']\n", + "X = df[feature_cols]\n", + "y = df['Target']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "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 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/303/Q1.ipynb b/submissions_extracted/303/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..429595c3687c7279952c9f6068b4c6a1aecaf356 --- /dev/null +++ b/submissions_extracted/303/Q1.ipynb @@ -0,0 +1,381 @@ +{ + "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", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Plot the target distribution (delivery_time)\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Drop the 'Order_ID' column from the data\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "\n", + "# Check for 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", + "# Drop missing values:\n", + "df = df.dropna()\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Check and remove duplicates if any exist\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df['Weather'] = le.fit_transform(df['Weather'])\n", + "df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n", + "df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n", + "df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])\n" + ], + "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: Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df\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", + "# The data is not imbalanced" + ], + "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 StratifiedKFold, train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "n_splits = 10\n", + "rf_mae = []\n", + "\n", + "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "\n", + " # Train\n", + " model = model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mea = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " rf_mae.append(mea)\n", + "\n", + "average_losses = np.mean(rf_mae, axis=0)\n", + "\n", + "print(\"Average MAE\", average_losses)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "feature_cols = \t['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred)\n", + "plt.title('Predicted Delivery Time')\n", + "plt.xlabel('Percentage')\n", + "plt.ylabel('Predicted value')\n", + "plt.legend()" + ], + "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", + "#!pip install catboost\n", + "from catboost import CatBoostRegressor\n", + "\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\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", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n", + "\n", + "\n", + "\n" + ], + "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/303/Q2.ipynb b/submissions_extracted/303/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cc142889b1d534fd81a2b23f8cb47fb7aee4ede6 --- /dev/null +++ b/submissions_extracted/303/Q2.ipynb @@ -0,0 +1,413 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True,num_workers=2)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False,num_workers=2)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\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": [ + "# 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", + " plt.imshow(images[i])\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\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\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", + " # 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", + " a4 = self.relu(self.layer4(a3))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer5(a4)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\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", + "from torch.optim import AdamW\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Running Model on:\", device)\n", + "\n", + "input_dim = 32 * 36 * 3\n", + "hidden_dim = 36\n", + "output_dim = 1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/303/Q3.ipynb b/submissions_extracted/303/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8b2d05053bb185d605269184f58fea6fd547205 --- /dev/null +++ b/submissions_extracted/303/Q3.ipynb @@ -0,0 +1,325 @@ +{ + "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", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "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", + "# Check for 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", + "for col in df.columns:\n", + " df[col.title()] = df[col.title()].fillna(df[col.title()].mean())\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "\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: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "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=2, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Target\")\n", + "\n", + "# There is target imbalance" + ], + "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)\n", + "y = df['Target'].astype(float)\n", + "\n", + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "#!pip install catboost\n", + "from catboost import CatBoostClassifier\n", + "\n", + "n_splits = 5\n", + "cb_accuracy = []\n", + "cb_f1 = []\n", + "\n", + "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + " model = CatBoostClassifier(verbose=0)\n", + "\n", + " # Train\n", + " model = model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " cb_accuracy.append(accuracy)\n", + " cb_f1.append(cb_f1)\n", + "\n", + "avg_accuracy = np.mean(cb_accuracy, axis=0)\n", + "avg_f1 = np.mean(cb_f1, axis=0)\n", + "\n", + "print(avg_accuracy)\n", + "print(avg_f1)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "feature_cols = \t['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#importance['feature'[0]" + ], + "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/304/Q1.ipynb b/submissions_extracted/304/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4beeef0393d57cc2c884b7cc45dbf505ac508f3b --- /dev/null +++ b/submissions_extracted/304/Q1.ipynb @@ -0,0 +1,400 @@ +{ + "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 os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "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": [ + "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", + "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 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", + "col_name = pd.DataFrame({\"col_name\": [\"Distance_km,Weather\", \"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\",\"Preparation_Time_min\",\"Courier_Experience_yrs\"\t,\"Delivery_Time\"]})\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder, LabelEncoder, OrdinalEncoder\n", + "\n", + "print('data before encoding:\\n',col_name )\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(col_name)\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.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": [ + "# 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": [ + "# Mean Squared Error in NumPy\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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/304/Q2.ipynb b/submissions_extracted/304/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d3c185dc1d201f56c476b9a5dc924a0e8be4e48d --- /dev/null +++ b/submissions_extracted/304/Q2.ipynb @@ -0,0 +1,368 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "print(\"Shape of x:\", x.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# 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", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\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:class SimpleNN(nn.Module):\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": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:# Device configuration\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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/304/Q3.ipynb b/submissions_extracted/304/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2bad4b0c08b65b87e1bbf7c93d8989ae3e319714 --- /dev/null +++ b/submissions_extracted/304/Q3.ipynb @@ -0,0 +1,341 @@ +{ + "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", + "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", + "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.\")\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", + "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": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " # sigmoid in NumPy\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\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" + ], + "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", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + " 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", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/305/Q1.ipynb b/submissions_extracted/305/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f87ea95a1f225cd989b41ee43dd980520d68f651 --- /dev/null +++ b/submissions_extracted/305/Q1.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from IPython.display import clear_output\n", + "import numpy as np\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "from sklearn.model_selection import KFold\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "clear_output()\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", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)x`" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Advertising.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df = df.drop(columns=\"Unnamed: 0\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "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": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\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": [ + "#Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n", + "#we can see that is not balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# 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": [ + "# Transmission distribution\n", + "transmission_counts = df.drop['transmission'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(transmission_counts.index, transmission_counts.values, color='teal')\n", + "plt.title('Transmission Distribution')\n", + "plt.xlabel('Transmission Type')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Year distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_cars['year'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Year Distribution')\n", + "plt.xlabel('Year')\n", + "plt.ylabel('Frequency')\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/305/Q2.ipynb b/submissions_extracted/305/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a59fcd2639b1ef521f6537785d72e6ff4f0e6c3 --- /dev/null +++ b/submissions_extracted/305/Q2.ipynb @@ -0,0 +1,391 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from torchvision.datasets import MNIST\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", + "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", + "# 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 = 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", + "# 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", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + " 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": [ + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " return z4\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + "\n", + " outputs = model(X_batch)\n", + "\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", + "\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", + "\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "learning_rate = 0.001\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3 * 32 * 32\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: S# Run Training\n", + "num_epochs = 15\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "criterion = nn.CrossEntropyLoss()\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", + "\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 her# 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/305/Q3.ipynb b/submissions_extracted/305/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..faae9abe9c9c43395643b605fc64a0fbdb3a9597 --- /dev/null +++ b/submissions_extracted/305/Q3.ipynb @@ -0,0 +1,267 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from IPython.display import clear_output\n", + "import numpy as np\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "from sklearn.model_selection import KFold\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import optuna\n", + "tqdm.pandas()\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "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", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\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": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\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": [ + "#Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df,\"B_1\")\n", + "#we can see that is not balanced\n", + "check_target_imbalance(df,\"P_2\")\n", + "check_target_imbalance(df,\"D_39\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"D_145\", axis=1)\n", + "y = df['D_145'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define classification models\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": [ + "# Year distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['year'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Year Distribution')\n", + "plt.xlabel('Year')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/306/Q1.ipynb b/submissions_extracted/306/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d9adbbc1f90e5a829ea9c42dd70cd54caa9d94c4 --- /dev/null +++ b/submissions_extracted/306/Q1.ipynb @@ -0,0 +1,373 @@ +{ + "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", + "\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", + "print(os.listdir(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(20)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=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 \t\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Drop rows where target (delivery time) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level', 'Courier_Experience_yrs'])\n", + "print(f\"After dropping missing Delivery_Time/Weather/Traffic_Level: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill Courier_Experience_yrs with mean\n", + "#df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean()[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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #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", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "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 tqdm import tqdm\n", + "\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "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", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " 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", + "# Make predictions and calculate MAE\n", + "valid_pred = model.predict(X_valid)\n", + "model_mae = mean_absolute_error(y_valid, valid_pred)\n", + "print(f\"Model MAE: {model_mae:.4f}\")\n" + ], + "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:\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + " kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = sklearn_mae(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(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/306/Q2.ipynb b/submissions_extracted/306/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c43e9ad98e28d972e9ebc1f51995abf14dc8a521 --- /dev/null +++ b/submissions_extracted/306/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", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import torch\n", + "from torch.optim import Adam\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", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "#in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Third hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 32 * 32 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 100 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n" + ], + "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", + "# 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/306/Q3.ipynb b/submissions_extracted/306/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..090d9c30779fe280c8397d15f01847f044d8c660 --- /dev/null +++ b/submissions_extracted/306/Q3.ipynb @@ -0,0 +1,281 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import os\n", + "\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", + "print(os.listdir(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", + "\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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n" + ], + "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", + "%pip install catboost\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "import optuna\n", + "tqdm.pandas()\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\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": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_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/307/Q1.ipynb b/submissions_extracted/307/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1232462ffde212c34f9e5dd687715194a8147ec --- /dev/null +++ b/submissions_extracted/307/Q1.ipynb @@ -0,0 +1,255 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task\n", + "delivery_path = os.path.join(path,'Q1_data.csv')\n", + "df_delivey = pd.read_csv(delivery_path)\n", + "\n", + "print(f\"Dataset shape: {delivery_path}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "delivery_path.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivey.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df_delivey.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivey['price'].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": [ + "\n", + "cols = ['Order_ID']\n", + "df_clean = df_delivey[cols].copy()\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "categorical_cols = ['Order_ID']\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 3:\n", + "\n", + "df_clean['Order'] = df_clean['order'] / (df_clean['order'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "X_train.head(1)\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: '\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_pokemon['delivey_time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery_time')\n", + "plt.xlabel('time')\n", + "plt.ylabel('time ')\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['sp_attack'].dropna(), bins=30, edgecolor='black', color='yellow')\n", + "plt.title('delivery_time')\n", + "plt.xlabel('deliveey_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/307/Q2.ipynb b/submissions_extracted/307/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..aeb98dd578caa3d90ba73d3ef534b965e53dccc9 --- /dev/null +++ b/submissions_extracted/307/Q2.ipynb @@ -0,0 +1,341 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "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)\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 batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)\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\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "test_loader = kagglehub.dataset_load(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\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", + "# Create a linear layer: 4 input features -> 1 output\n", + "linear = nn.Linear(in_features=4, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n" + ], + "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:" + ], + "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/307/Q3.ipynb b/submissions_extracted/307/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..691dcbcf3e17bc66518c7e8513f3373e354f4949 --- /dev/null +++ b/submissions_extracted/307/Q3.ipynb @@ -0,0 +1,200 @@ +{ + "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", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df = df.drop(columns=\"Unnamed: 0\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "read_path.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "read_path.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "read_path.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" + ], + "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", + "df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\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": [ + "# 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/308/Q1.ipynb b/submissions_extracted/308/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3a2c81676b49c0d36287cc50be41e1364673e4d2 --- /dev/null +++ b/submissions_extracted/308/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 numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "# Load the dataset\n", + "cars_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(cars_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "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 LabelEncoder,OneHotEncoder\n", + "print(\"Separating target variable and features...\")\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "\n", + "print(\"Verification of encoded data shapes:\")\n", + "print(f\"Shape of X_encoded: {X_encoded.shape}\")\n", + "print(f\"Shape of y_encoded: {y_encoded.shape}\")\n", + "\n", + "print(\"First 5 rows of X_encoded:\")\n", + "display(X_encoded.head())\n", + "print(\"First 5 elements of y_encoded:\")\n", + "print(y_encoded[:5])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "print(\"\\nValue counts for the target variable 'Delivery_Time':\")\n", + "class_distribution = df['Delivery_Time'].value_counts()\n", + "print(class_distribution)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(6, 4))\n", + "sns.countplot(data=df, x='Delivery_Time')\n", + "plt.title('Distribution of Target Variable (Class)')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(\"Splitting data into training and testing sets...\")\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n", + "\n", + "print(\"Data split successful.\")\n", + "print(f\"Shape of X_train: {X_train.shape}\")\n", + "print(f\"Shape of X_test: {X_test.shape}\")\n", + "print(f\"Shape of y_train: {y_train.shape}\")\n", + "print(f\"Shape of y_test: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "print(\"Initializing models and K-Fold cross-validation...\")\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "# Determine the number of classes for one-hot encoding\n", + "num_classes = len(np.unique(y_encoded))\n", + "\n", + "# 1. Initialize the machine learning models\n", + "models = {\n", + "\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n", + "\n", + "}\n", + "\n", + "# 2. Create a KFold object\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "\n", + "# 4. For each model:\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Convert y_val_fold (true labels) into a one-hot encoded format\n", + " y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n", + "\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + " loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n", + " fold_losses.append(loss)\n", + "\n", + " # Calculate the average loss for the model\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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/308/Q2.ipynb b/submissions_extracted/308/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7a1a78b0b5bad595ab755e773dd393488812f649 --- /dev/null +++ b/submissions_extracted/308/Q2.ipynb @@ -0,0 +1,453 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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}\") # (C, H, W)\n", + "\n", + "'''When you load batches, it becomes:\n", + "(batch_size, 1, 28, 28)'''\n", + "\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n" + ], + "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", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + "\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", + " # 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", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\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 = 1*28*28 # 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}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:# TODO: choose number of epochs, increase it if you have gpus :)\n", + "from torch.optim import AdamW\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", + "# 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": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/308/Q3.ipynb b/submissions_extracted/308/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d8bd9b4482c6fae046db82adf4d2e62541f073f0 --- /dev/null +++ b/submissions_extracted/308/Q3.ipynb @@ -0,0 +1,464 @@ +{ + "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", + "\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)\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", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in df:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# BCE in NumPy\n", + "def binary_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15 # Very small number to prevent log(0)\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n", + "\n", + " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n", + " return loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" F1-Score: {np.mean(lr_f1):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Calculate the majority class baseline\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "\n", + "print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n", + "print(f\"Baseline F1-Score: {baseline_f1:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "\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/309/Q1.ipynb b/submissions_extracted/309/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c5502888906afe8a8210646f97a345df09e494cd --- /dev/null +++ b/submissions_extracted/309/Q1.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\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", + "cars_path = os.path.join(path, 'Q1_data.csv')\n", + "df_cars = pd.read_csv(cars_path)\n", + "\n", + "print(f\"Dataset shape: {df_cars.shape}\")\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check data types and structure\n", + "df_cars.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_cars.isnull().sum() / len(df_cars)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:# Descriptive statistics for numerical columns\n", + "df_cars.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#5. Plot the target distribution (delivery_time)\n", + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_cars['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 'Order_ID' column from the data\n", + "df_clean =(df_cars['Order_ID'].dropna())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "# 2️ Check for missing values\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " # Count number of missing values in each column\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " # If any missing values exist\n", + "\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + "\n", + " else:\n", + " # If no missing values exist\n", + "\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_cars)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " # Count duplicated row\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "\n", + " if duplicates > 0:\n", + " # If duplicates exist\n", + "\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " # If no duplicates exist\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_cars)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "# Encode categorical columns - converts text to integers\n", + "# Encode type columns\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'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "print('data before scaling:\\n',df_cars) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_cars) # 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": [ + "# Replace 'target_column' with your actual target name\n", + "df_cars['target_column'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_cars.drop(\"target\", axis=1).astype(float)\n", + "y = df_cars[\"target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 1: 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_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + " # Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n", + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "mse = mean_squared_error(y_test.numpy(), predictions)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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/309/Q2.ipynb b/submissions_extracted/309/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e0d1ebcefe1224e0c5bc9cd068aa3dd8ccb80917 --- /dev/null +++ b/submissions_extracted/309/Q2.ipynb @@ -0,0 +1,466 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Training dataset\n", + "train_dataset = CIFAR10(\n", + " root='./datasets', # Directory to store dataset\n", + " # مسار حفظ البيانات\n", + " train=True, # Use training data\n", + " # نستخدم بيانات التدريب\n", + " transform=to_tensor, # Convert images to tensors\n", + " # تحويل الصور إلى Tensor\n", + " download=True # Download if not already downloaded\n", + " # تحميل البيانات إذا غير موجودة\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = CIFAR10(\n", + " root='./datasets', # Same dataset directory\n", + " # نفس مسار البيانات\n", + " train=False, # Use test data\n", + " # نستخدم بيانات الاختبار\n", + " transform=to_tensor, # Convert images to tensors\n", + " # تحويل الصور إلى Tensor\n", + " download=True # Download if needed\n", + " # تحميلها إذا لزم\n", + ")\n", + "\n", + "# Get one sample image and its label from training data\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "# Print the shape of the image tensor\n", + "# طباعة شكل الصورة بعد التحويل إلى Tensor\n", + "print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n", + "\n", + "# Print the label (class index)\n", + "# طباعة رقم الفئة (التصنيف)\n", + "print(f\"Label: {sample_label}\")\n", + "\n", + "# DataLoader for training data\n", + "#\n", + "# إنشاء DataLoader لبيانات التدريب\n", + "train_loader = DataLoader(\n", + " train_dataset, # Training dataset\n", + " # بيانات التدريب\n", + " batch_size=32, # Number of samples per batch\n", + " # عدد الصور في كل دفعة\n", + " shuffle=True, # Shuffle data each epoch\n", + " # خلط البيانات كل مرة (مهم للتدريب)\n", + " num_workers=2 # Number of subprocesses for data loading\n", + " # عدد العمليات لتحميل البيانات\n", + ")\n", + "\n", + "# DataLoader for test data\n", + "# إنشاء DataLoader لبيانات الاختبار\n", + "test_loader = DataLoader(\n", + " test_dataset, # Test dataset\n", + " # بيانات الاختبار\n", + " batch_size=32, # Same batch size\n", + " # نفس حجم الدفعة\n", + " shuffle=False, # No shuffling during evaluation\n", + " # لا نخلط البيانات أثناء التقييم\n", + " num_workers=2 # Data loading workers\n", + " # عمليات تحميل البيانات\n", + ")\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "# أخذ أول batch من بيانات التدريب (للفحص فقط)\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "# Print input batch shape\n", + "# طباعة شكل بيانات الإدخال\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "\n", + "# Print labels batch shape\n", + "# طباعة شكل التسميات\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# 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": [ + "# 5. Display sample images\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.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", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n", + "\n", + " # Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\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)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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", + "# 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/309/Q3.ipynb b/submissions_extracted/309/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8b2f7f6df7f6a8878daaca3a83bbdc372140d5d6 --- /dev/null +++ b/submissions_extracted/309/Q3.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pokemon_path = os.path.join(path, 'Q3_data.csv')\n", + "df_pokemon = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {df_pokemon.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_pokemon.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_pokemon.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df_pokemon.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "df_pokemon.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_pokemon.isnull().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols=['P_2 ', 'D_39 ', 'B_1 ', 'B_2 ', 'R_1']\n", + "df_clean = df_pokemon[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['P_2', 'B_2 ']:\n", + " df_pokemon[col] = df_pokemon[col].fillna('unknown')\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "df_pokemon['cylinders'] = df_pokemon['cylinders'].fillna(df_pokemon['cylinders'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_pokemon.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 4️ Check for duplicate samples\n", + "# فحص وجود عينات مكررة في البيانات\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " # Count duplicated rows\n", + " # حساب عدد الصفوف المكررة\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "\n", + " if duplicates > 0:\n", + " # If duplicates exist\n", + " # إذا وُجدت عينات مكررة\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " # حذف العينات المكررة\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " # If no duplicates exist\n", + " # إذا لا توجد عينات مكررة\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_pokemon)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', df_pokemon) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(df_pokemon[\"Animal\"]) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Scale features - fit on train, transform both\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import StandardScaler\n", + "# EN: StandardScaler transforms features to have mean=0 and std=1\n", + "numerical_cols = df_pokemon.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"status\")\n", + "# EN: Select all numeric columns EXCEPT the target column \"status\"\n", + "# IMPORTANT: We do NOT scale the target (label)\n", + "# مهم: لا نقوم بعمل scaling للـ target لأنه يمثل الفئة (0/1) وليس feature\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "# EN: Create scaler object\n", + "\n", + "\n", + "df_pokemon[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "# EN: Fit scaler on numeric features and transform them\n", + "# AR: تعلم الإحصائيات من البيانات (mean/std) ثم تطبيق التحويل على الأعمدة الرقمية\n", + "# Result: features become standardized\n", + "# النتيجة: الخصائص تصبح على نفس المقياس\n", + "\n", + "\n", + "df_pokemon.head()\n", + "# EN: Show first rows after scaling\n", + "\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", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y= X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + " from catboost import CatBoostClassifier\n", + " #: CatBoost boosting classifier (robust)\n", + "\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " # EN: suppress log\n", + " n_estimators=320,\n", + " # EN: number of boosting iterations\n", + " max_depth=4\n", + " # EN: tree depth\n", + " # AR: عمق الشجرة\n", + " )\n", + " all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " # EN: Initialize lists to store metrics across folds\n", + " # AR: تهيئة قوائم لتخزين نتائج كل fold\n", + "\n", + " all_results[name] = {\n", + " 'accuracy': [], # EN: overall correctness |\n", + " 'precision': [], # EN: correctness of positive predictions |\n", + " 'recall': [], # EN: ability to find positives |\n", + " 'f1': [] # EN: balance precision & recall |\n", + " }\n", + "\n", + "\n", + "## Print average evaluation metrics for each model\n", + "# طباعة متوسط مقاييس التقييم لكل نموذج بعد K-Fold Cross-Validation\n", + "\n", + "for model_name in all_results:\n", + " # Loop through each trained model\n", + " # المرور على كل نموذج تم تدريبه وتقييمه\n", + "\n", + " print(f\"\\n{model_name}:\")\n", + " # Print model name\n", + " # طباعة اسم النموذج\n", + "\n", + "\n", + " print(f\" accuracy : {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " # EN: Average Mean Squared Error across all folds\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"golden feature\"+ )\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/31/Q1.ipynb b/submissions_extracted/31/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e4357e958d26adf5d1bed5808d35cdf6a02243c --- /dev/null +++ b/submissions_extracted/31/Q1.ipynb @@ -0,0 +1,186 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "\n", + "data = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "\n", + "data\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "head = data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info(10)" + ], + "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", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.show(data.X_axis , data.Y_axis)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "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", + "from sklearn import linear_regression" + ], + "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/31/Q2.ipynb b/submissions_extracted/31/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1cb74906a93f580ddf44e08d589fd5986d496855 --- /dev/null +++ b/submissions_extracted/31/Q2.ipynb @@ -0,0 +1,198 @@ +{ + "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 as tr\n", + "\n", + "X_tensor = X.ternsor()\n", + "\n", + "Y_tensor = Y.tensor()\n", + "\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/31/Q3.ipynb b/submissions_extracted/31/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..12cfb74f6d460b527ee77f2a98738b12a0080748 --- /dev/null +++ b/submissions_extracted/31/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", + "data = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n", + "\n", + "data" + ], + "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(200)" + ], + "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:" + ], + "execution_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:\n", + "from sklearn import k-fold\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/310/Q1.ipynb b/submissions_extracted/310/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..404d647f0f89e23c915a9df779799304a50a4612 --- /dev/null +++ b/submissions_extracted/310/Q1.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "# Task 1: Write your code here:" + ], + "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", + "\n", + "check_target_distribution(df,\"Delivery_Time\")\n", + "\n", + "\n", + "\n" + ], + "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.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code h\n", + "df.duplicated().sum()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "#colm = df['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "x = df['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "y = df['Delivery_Time']\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoder(x[1,2,3,4])\n", + "\n", + "\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", + "x = df['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "y = df['Delivery_Time']\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "\n" + ], + "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 train_test_split\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500)\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int)\n", + "X, y = X_clf.copy(), y_clf.copy()\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 # preserve class distribution\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "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:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(X_train, label='Train Loss')\n", + "plt.plot(y_train, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + "\n", + "check_target_distribution(df,\"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/310/Q2.ipynb b/submissions_extracted/310/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8894fac1b2d0a0e0a6e8c6a80eae82edc00629cd --- /dev/null +++ b/submissions_extracted/310/Q2.ipynb @@ -0,0 +1,277 @@ +{ + "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 Numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "X = df.drop(\"Weather Type\",axis=1)\n", + "y = df['Weather Type']\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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": [ + "# 3. Create DataLoaders\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", + "# 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", + "pach.shep()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + ".Display()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "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": [ + "# Task 2: Write your training loop here:\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " 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 3: Write your validation loop here:\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)))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss,\n", + " optimizer:optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "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=(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 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/310/Q3.ipynb b/submissions_extracted/310/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1de9945f383b49952b4453b41f27047119e8a9c1 --- /dev/null +++ b/submissions_extracted/310/Q3.ipynb @@ -0,0 +1,194 @@ +{ + "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('dadt.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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', categories) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(categories[\"Animal\"]) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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/311/Q1.ipynb b/submissions_extracted/311/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e7031fef9cb41835459a5adb8f8a46b25dc06429 --- /dev/null +++ b/submissions_extracted/311/Q1.ipynb @@ -0,0 +1,431 @@ +{ + "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.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# df_food.drop(df_food['Order_ID'], axis=1)\n", + "df_food = df_food.drop(['Order_ID'], axis=1)\n", + "df_food.head(5)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df_food.copy()\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "df_clean.head(5)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "for col in cols:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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_food.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": [ + "# df_clean.drop_duplicates(inplace=True)" + ], + "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": [ + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_food.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()" + ], + "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(\"Delivery Time Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "# X = df_clean\n", + "# y = df_clean['price']\n", + "\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1)\n", + "y = df_clean[\"Delivery_Time\"]\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Delivery_Time in train: {y_train.sum()}, in test: {y_test.sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# lr_accuracy = []\n", + "# lr_precision = []\n", + "# lr_recall = []\n", + "# lr_f1 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "# for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + "# # Calculate evaluation metrics\n", + "# accuracy = accuracy_score(y_test, y_pred)\n", + "# precision = precision_score(y_test, y_pred, zero_division=0)\n", + "# recall = recall_score(y_test, y_pred, zero_division=0)\n", + "# f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "# # Store results\n", + "# lr_accuracy.append(accuracy)\n", + "# lr_precision.append(precision)\n", + "# lr_recall.append(recall)\n", + "# lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "# Feature importance\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/311/Q2.ipynb b/submissions_extracted/311/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..339ef0daf8790930f904d436b58cadd954363933 --- /dev/null +++ b/submissions_extracted/311/Q2.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch.nn.functional as F\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": [ + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import DataLoader , TensorDataset\n", + "import torch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # 5. Display sample images\n", + "# import matplotlib.pyplot as plt\n", + "\n", + "# images, labels = next(iter(train_loader))\n", + "\n", + "# # Display the first 6 images in the batch\n", + "# plt.figure(figsize=(8, 6))\n", + "\n", + "# for i in range(6):\n", + "# plt.subplot(2, 3, i + 1)\n", + "# plt.imshow(images[i].squeeze(), cmap='gray')\n", + "# plt.title(f\"Label: {labels[i].item()}\")\n", + "# plt.axis('off')\n", + "\n", + "# plt.tight_layout()\n", + "# plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + "# # Set the model to training mode\n", + "# model.train()\n", + "\n", + "# running_loss = 0.0\n", + "\n", + "# for X_batch, y_batch in train_loader:\n", + "# # Move batch to the selected device\n", + "# X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + "# y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + "# # Forward pass (outputs are logits)\n", + "# outputs = 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 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 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}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Run Training\n", + "# train_losses = []\n", + "# val_losses = []\n", + "# val_accuracies = []\n", + "\n", + "# print('Starting Training...')\n", + "# for epoch in range(num_epochs):\n", + "# # Train one epoch\n", + "# train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + "# # Validate\n", + "# val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + "# train_losses.append(train_loss)\n", + "# val_losses.append(val_loss)\n", + "# val_accuracies.append(val_accuracy)\n", + "\n", + "# print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "# print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 1: Write your code here:\n", + "# 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/311/Q3.ipynb b/submissions_extracted/311/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59ab3cdd6e8d2b19dc89752b936d29818349269c --- /dev/null +++ b/submissions_extracted/311/Q3.ipynb @@ -0,0 +1,220 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "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(\"Delivery Time 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:" + ], + "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/312/Q1.ipynb b/submissions_extracted/312/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5bb4e1e1d9b227b20a65d737c9f0004cc788ce5d --- /dev/null +++ b/submissions_extracted/312/Q1.ipynb @@ -0,0 +1,703 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n" + ], + "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": [ + "\n", + "# Task 1: Write your code here:\n", + "\n", + "\n", + "\n", + "\n", + "# Load the CSV file\n", + "pokemon_path = os.path.join(path, 'Q1_data.csv')\n", + "df_pokemon = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {df_pokemon.shape}\")\n", + "df_pokemon.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_pokemon.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_pokemon.info()" + ], + "execution_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": [ + "## ================================\n", + "## CHECK TARGET IMBALANCE\n", + "## ================================\n", + "\n", + "## This function checks whether the target variable is imbalanced\n", + "## by printing class proportions and plotting their distribution.\n", + "## Class imbalance is important because it affects model evaluation.\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + "\n", + " ## Print a title to clearly indicate the output\n", + " print(\"Target Distribution:\\n\")\n", + "\n", + " ## Count the proportion of each class (normalized = percentages)\n", + " ## This helps us see how frequent each class is\n", + " proportions = df[target_column].value_counts(normalize=True)\n", + " print(proportions)\n", + "\n", + " ## Create a bar plot to visualize the class distribution\n", + " ## This makes imbalance easy to see visually\n", + " sns.countplot(x=df[target_column])\n", + "\n", + " ## Add a title to the plot for clarity\n", + " plt.title(\"Target Distribution\")\n", + "\n", + " ## Display the plot\n", + " plt.show()\n", + "\n", + "\n", + "## ================================\n", + "## APPLY THE FUNCTION\n", + "## ================================\n", + "\n", + "## Call the function on the training dataset\n", + "## \"Score\" is the target column (Home win / Draw / Away win)\n", + "check_target_imbalance(df_pokemon, 'Delivery_Time')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Target distribution\n", + "print(f\"delivery_time: {df_pokemon['Delivery_Time'].sum()}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_pokemon.drop(\"Order_ID\",axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_pokemon)" + ], + "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_pokemon)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Do we have categorical columns?\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df_pokemon)\n", + "print(encode_categorical_columns(df_pokemon))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "categorical=df_pokemon.select_dtypes(include=[\"object\"]).columns\n", + "print('data before encoding:\\n', categorical) #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": [ + "##Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "df_pokemon\n", + "print('data before scaling:\\n', df_pokemon) #show before scaling\n", + "df_pokemon = 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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "##Check for target imbalance\n", + "###and state if it is imbalanced or not (keep this cell empty if not needed)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + "\n", + " ## Print a title to clearly indicate the output\n", + " print(\"Target Distribution:\\n\")\n", + "\n", + " ## Count the proportion of each class (normalized = percentages)\n", + " ## This helps us see how frequent each class is\n", + " proportions = df[target_column].value_counts(normalize=True)\n", + " print(proportions)\n", + "\n", + " ## Create a bar plot to visualize the class distribution\n", + " ## This makes imbalance easy to see visually\n", + " sns.countplot(x=df[target_column])\n", + "\n", + " ## Add a title to the plot for clarity\n", + " plt.title(\"Target Distribution\")\n", + "\n", + " ## Display the plot\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " 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 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "X = df_pokemon.drop('Delivery_Time', axis=1)\n", + "y = df_pokemon['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "## ==================================================\n", + "## SPLIT FEATURES AND TARGET\n", + "## ==================================================\n", + "y = df_pokemon['Delivery_Time']\n", + "## X contains all input features except the target column\n", + "X = df_pokemon.drop(\"Delivery_Time\", axis=1)\n", + "\n", + "## y contains the target variable we want to predict\n", + "\n", + "\n", + "\n", + "## ==================================================\n", + "## MAJORITY CLASS BASELINE\n", + "## ==================================================\n", + "\n", + "## Find the most frequent class in the target variable\n", + "majority_class = y.value_counts().idxmax()\n", + "\n", + "## Create baseline predictions where all samples are predicted\n", + "## as the majority class\n", + "baseline_pred = [majority_class] * len(y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "## ======================\n", + "## 11) EVALUATE MODEL (MAE)\n", + "## ======================\n", + "## Predict on validation set\n", + "valid_pred = model.predict(X_valid)\n", + "\n", + "## Calculate MAE\n", + "model_mae = mean_absolute_error(y_valid, valid_pred)\n", + "print(f\"Model MAE: {model_mae:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\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", + "\n", + "\n", + "sklearn_models = {\n", + "\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mse = mean_squared_error(y_test, y_pred)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "\n", + "print(\"MSE :\", mse)\n", + "print(\"MAE :\", mae)\n", + "print(\"RMSE:\", rmse)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.ensemble import RandomForestRegressor\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + "\n", + "\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = 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", + "\n", + "## -----------------------------\n", + "## 5) Plot feature importance\n", + "## -----------------------------\n", + "\n", + "## plt.figure(figsize=(18, 14)):\n", + "## - sets the size of the plot\n", + "## - larger size improves readability when many features exist\n", + "\n", + "features, importances = zip(*sklearn_models )\n", + "\n", + "plt.figure(figsize=(18, 14))\n", + "\n", + "## plt.barh(...):\n", + "## - creates a horizontal bar chart\n", + "## - y-axis: feature names\n", + "## - x-axis: importance scores\n", + "plt.barh(features, importances, color=\"orange\")\n", + "\n", + "## plt.xlabel:\n", + "## - labels the x-axis\n", + "## - shows that values represent importance scores\n", + "plt.xlabel(\"Importance Score\")\n", + "\n", + "## plt.ylabel:\n", + "## - labels the y-axis\n", + "## - shows feature names\n", + "plt.ylabel(\"Features\")\n", + "\n", + "\n", + "## plt.gca().invert_yaxis():\n", + "## - inverts the y-axis\n", + "## - ensures the most important features appear at the top\n", + "plt.gca().invert_yaxis()\n", + "\n", + "## plt.show():\n", + "## - displays the plot on the screen\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:\n", + "\n", + "## ==================================================\n", + "## TRAIN MULTIPLE MODELS + K-FOLD CV + F1-SCORE\n", + "## ==================================================\n", + "## Goal:\n", + "## - Train several classifiers (LogReg, RandomForest, CatBoost)\n", + "## - Build a soft VotingClassifier (ensemble)\n", + "## - Evaluate each model using 5-Fold Cross-Validation\n", + "## - Use weighted F1-score as the main metric\n", + "\n", + "import numpy as np\n", + "\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "## -----------------------------\n", + "## 1) Define classification models\n", + "## -----------------------------\n", + "\n", + "## Create a dictionary of models so we can evaluate them in a loop\n", + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100, random_state=42),\n", + " \"CatBoost Classifier\": CatBoostClassifier(verbose=0, random_state=42)\n", + "}\n", + "\n", + "## -----------------------------\n", + "## 2) Build an Ensemble (Soft Voting)\n", + "## -----------------------------\n", + "\n", + "## Soft voting = combines predicted probabilities (better when models are strong)\n", + "models[\"Ensemble\"] = VotingClassifier(\n", + " estimators=[\n", + " (\"cb\", models[\"CatBoost Classifier\"]),\n", + " (\"lr\", models[\"Logistic Regression\"]),\n", + " (\"rf\", models[\"Random Forest Classifier\"])\n", + " ],\n", + " voting=\"soft\"\n", + ")\n", + "\n", + "## -----------------------------\n", + "## 3) K-Fold Cross Validation (K=5)\n", + "## -----------------------------\n", + "\n", + "## KFold splits the dataset into 5 parts and evaluates 5 times\n", + "## shuffle=False matches the test requirement (no shuffling)\n", + "kf = KFold(n_splits=5, shuffle=False)\n", + "\n", + "## -----------------------------\n", + "## 4) Evaluate each model using F1-score\n", + "## -----------------------------\n", + "\n", + "for model_name, model in models.items():\n", + "\n", + " ## Store F1 score from each fold\n", + " scores_f1 = []\n", + "\n", + " ## Split indices into train and test folds\n", + " for train_idx, test_idx in kf.split(X, y):\n", + "\n", + " ## Build fold train/test data\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 on training fold\n", + " model.fit(X_train, y_train)\n", + "\n", + " ## Predict on the test fold\n", + " y_pred = model.predict(X_test)\n", + "\n", + " ## Compute weighted F1-score (handles class imbalance better than accuracy)\n", + " f1 = f1_score(y_test, y_pred, average=\"weighted\")\n", + " scores_f1.append(f1)\n", + "\n", + " ## Print mean F1-score across the 5 folds\n", + " print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print()\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/312/Q2.ipynb b/submissions_extracted/312/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2284f9fdd09cb378d9df245c4d804d5356e8cd47 --- /dev/null +++ b/submissions_extracted/312/Q2.ipynb @@ -0,0 +1,443 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "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": [ + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "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", + "\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", + " # 3linear 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, 2)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Second hidden layer\n", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "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: Define the device, model, loss function, and optimizer\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 256 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n" + ], + "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_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:\n", + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "mse = mean_squared_error(y_test.numpy(), predictions)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")\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/312/Q3.ipynb b/submissions_extracted/312/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..47956a415e4e53b26feb31ba117bb60f3fdbcf8a --- /dev/null +++ b/submissions_extracted/312/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 numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "# Load the CSV file\n", + "pokemon_path = os.path.join(path, 'Q3_data.csv')\n", + "df_pokemon = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {df_pokemon.shape}\")\n", + "df_pokemon.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_pokemon.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_pokemon.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_pokemon.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Check missing values\n", + "missing_values = df_pokemon.isnull().sum()\n", + "print(\"Columns with missing values:\")\n", + "print(missing_values[missing_values > 0])\n", + "\n", + "# Fill missing values with mean for each column\n", + "df_pokemon= df_pokemon.fillna(df_pokemon.mean())" + ], + "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_pokemon)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# 3. Do we have categorical columns?\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df_pokemon)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_pokemon) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_pokemon) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling\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", + "def check_target_imbalance(df, target_column):\n", + "\n", + " ## Print a title to clearly indicate the output\n", + " print(\"Target Distribution:\\n\")\n", + "\n", + " ## Count the proportion of each class (normalized = percentages)\n", + " ## This helps us see how frequent each class is\n", + " proportions = df[target_column].value_counts(normalize=True)\n", + " print(proportions)\n", + "\n", + " ## Create a bar plot to visualize the class distribution\n", + " ## This makes imbalance easy to see visually\n", + " sns.countplot(x=df[target_column])\n", + "\n", + " ## Add a title to the plot for clarity\n", + " plt.title(\"Target Distribution\")\n", + "\n", + " ## Display the plot\n", + " plt.show()" + ], + "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)\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", + "\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", + "## SPLIT FEATURES AND TARGET\n", + "## ==================================================\n", + "y = df_pokemon['Delivery_Time']\n", + "## X contains all input features except the target column\n", + "X = df_pokemon.drop(\"Delivery_Time\", axis=1)\n", + "\n", + "## y contains the target variable we want to predict\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "importance = pd.DataFrame({\n", + " \"feature\": features,\n", + " \"importance\": model.feature_importances_\n", + "})\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/313/Q1.ipynb b/submissions_extracted/313/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..85049407cae4d7cbe742a0774254d54e9b3f4f18 --- /dev/null +++ b/submissions_extracted/313/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", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Read the dataset Q1_data.csv using read_csv()\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "data = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Inspect the first few rows using head()\n", + "\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Display dataset information using info()\n", + "\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Show statistical description using describe()\n", + "\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Plot the target distribution (delivery_time)\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(data, \"Delivery_Time\")" + ], + "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 = data.drop(\"Order_ID\", axis=1)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Handle missing values appropriately\n", + "# (Hint: I guess you want to have a closer look at the\n", + "# columns with missing values :) )\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna()\n", + "check_missing_values(df)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Check and remove duplicates if any exist\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop_duplicates(inplace=False)\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Encode categorical variables if needed (Bonus if used One Hot Encoding)\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", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']\n", + "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_squared_error as sklearn_mse\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_mse = []\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)\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", + "\n", + " # Store results\n", + " lr_mse.append(mse)\n", + "\n", + "print(f\" MSE: {np.mean(lr_mse)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.linear_model import Ridge, Lasso\n", + "\n", + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n", + "}\n", + "coeffs = {\"Lasso\": Lasso(alpha=1.0, max_iter=10000), \"Ridge\" :Ridge(alpha=1.0, max_iter=10000) }\n", + "\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/313/Q2.ipynb b/submissions_extracted/313/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7450ef770c664c8eac7b243cce0001a1e9fbf9c6 --- /dev/null +++ b/submissions_extracted/313/Q2.ipynb @@ -0,0 +1,374 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\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": [ + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # 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", + " output = self.relu(z4)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " 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", + " avg_loss = running_loss / len(test_loader)\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Define the device, model, loss function, and optimizer\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 15 # Design choice\n", + "output_dim = 1 # Age\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "criterion = nn.MSELoss()\n", + "\n", + "learning_rate = 0.001\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "print(model)" + ], + "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 = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\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/313/Q3.ipynb b/submissions_extracted/313/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..089dc28ac655dd3450ca8a57dd358e8b380c6929 --- /dev/null +++ b/submissions_extracted/313/Q3.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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "data = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(len(data))\n", + "data.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = data.dropna(axis=1)\n", + "check_missing_values(df)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "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\")\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", + "print(\"\\nValue counts for the target variable 'class':\")\n", + "class_distribution = df['Target'].value_counts()\n", + "print(class_distribution)\n", + "\n", + "# Imbalnced !!!!!" + ], + "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", + "y.head(50)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install kagglehub catboost lightgbm tqdm -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "\n", + "n_splits = 5 # K=3 Folds\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "sr_results = {'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", + " model = CatBoostRegressor(verbose=0)\n", + " model.fit(X_train, y_train)\n", + "\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')\n", + "\n", + " # Store results\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/314/Q1.ipynb b/submissions_extracted/314/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5be9daa181ae34fa5b28e95469fd7959b48243e3 --- /dev/null +++ b/submissions_extracted/314/Q1.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\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", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(df['Delivery_Time'].dropna())\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop('Order_ID', axis=1)\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']).copy()\n", + "\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df['Delivery_Time'].mean()).copy()\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", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder,OneHotEncoder #import LabelEncoder\n", + "\n", + "#print('data before encoding:\\n', df_clean.head()) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "#df_clean['Traffic_Level'] = label_encoder.fit_transform(df_clean[\"Traffic_Level\"]) # Apply fit_transform to the column\n", + "\n", + "\n", + "cat_cols= df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "one_hot = OneHotEncoder(sparse_output=False)\n", + "for col in cat_cols:\n", + " df_clean[col] = label_encoder.fit_transform(df_clean[col])\n", + "\n", + "print('\\nData after 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 #import StandardScaler\n", + "features= ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#no need cause it's regression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\",axis=1)\n", + "y = df_clean['Delivery_Time']" + ], + "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", + "# 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", + "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", + "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_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()\n" + ], + "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(y_pred, bins=50, edgecolor='black', color='green')\n", + "plt.title('Prediction Hist')\n", + "plt.xlabel('Prediction')\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/314/Q2.ipynb b/submissions_extracted/314/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6d9f34730c2b24c9c3a500f9375a0093caf14d1b --- /dev/null +++ b/submissions_extracted/314/Q2.ipynb @@ -0,0 +1,355 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# transform to tensors\n", + "X_train_tens = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tens = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tens = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tens = 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", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train_tens, y_train_tens)\n", + "test_dataset = TensorDataset(X_test_tens, y_test_tens)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\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", + "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", + "plt.imshow(X_batch[0].cpu().permute(1,2,0))\n", + "plt.axis('off')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\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\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", + " # Second hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " output = self.layer3(a3)\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " # Reshape square images into flattened vectors\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # 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():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " # Reshape square images into flattened vectors\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Accuracy calculation\n", + " correct += (outputs == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36 #images flattened\n", + "hidden_dim = 20\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", + "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 5: Start training for 20 epochs:\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "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/314/Q3.ipynb b/submissions_extracted/314/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9360ce87b0b124fb06dadaa4e70c828d70ef525f --- /dev/null +++ b/submissions_extracted/314/Q3.ipynb @@ -0,0 +1,220 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.fillna(0).copy()\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", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "#print('data before encoding:\\n', df_clean.head()) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "\n", + "cat_cols= df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in cat_cols:\n", + " df_clean[col] = label_encoder.fit_transform(df_clean[col])\n", + "\n", + "print('\\nData after encoding:\\n', df_clean.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "features= df_clean.select_dtypes(include=[\"float64\",'int64']).columns.drop(['Target'])\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #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:" + ], + "execution_count": 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/315/Q1.ipynb b/submissions_extracted/315/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8ed655b3c36ae0e2f1251ce34a7245ad306e4b0b --- /dev/null +++ b/submissions_extracted/315/Q1.ipynb @@ -0,0 +1,358 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "exam_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(exam_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", + "# target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('X')\n", + "plt.ylabel('Y')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean.drop(columns=[\"Order_ID\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "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", + "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['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_clean[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", + "# Define features and target\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Scale features - fit on train, transform both\n", + "from sklearn.model_selection import train_test_split, KFold\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.ensemble import RandomForestRegressor\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": [ + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import numpy as np\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "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", + "transmission_counts = df_clean['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(y_test, y_pred, color='teal')\n", + "plt.title('Delivery Time Prediction')\n", + "plt.xlabel('X')\n", + "plt.ylabel('Y')\n", + "plt.xticks(rotation=45)\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/315/Q2.ipynb b/submissions_extracted/315/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3db868778e00497293895c988fe57bf4ebb7750e --- /dev/null +++ b/submissions_extracted/315/Q2.ipynb @@ -0,0 +1,427 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "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", + "# 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", + "\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", + "# 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": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\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", + "import torch\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "from torch.optim import AdamW\n", + "learning_rate = 0.001\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)\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": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs= 20\n", + "learning_rate=0.001\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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/315/Q3.ipynb b/submissions_extracted/315/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..90b40b15f0975f48a14e31599b4f7a19e5b4537d --- /dev/null +++ b/submissions_extracted/315/Q3.ipynb @@ -0,0 +1,427 @@ +{ + "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", + "exam_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(exam_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_clean = df.copy()\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in df_clean:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#not needed since there's no categorical data\n", + "\n", + "df_clean.info()" + ], + "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_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_clean[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Target\")" + ], + "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": [ + "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": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "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", + "\n", + "sklearn_models = {\n", + "\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4 )}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from tqdm import tqdm\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", + "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": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " 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": [ + "import numpy as np\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Calculate average loss across folds\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols= []\n", + "for col in df_clean:\n", + " feature_cols.append(col)\n", + "\n", + "feature_cols.pop()\n", + "print(feature_cols)" + ], + "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=(100, 60))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"P_2 is the golden feature\")\n", + "print(df_clean['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/316/Q1.ipynb b/submissions_extracted/316/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f77c6be1136b0b441e40f93b0daa0bd096897fc4 --- /dev/null +++ b/submissions_extracted/316/Q1.ipynb @@ -0,0 +1,274 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "# Task 1: Write your code here:\n", + "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_data_path)# YOUR CODE HERE\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", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=[6,6])\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='Black')\n", + "plt.title('Target Distribution')\n", + "plt.ylabel('Freq')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_no_order_id = df.drop('Order_ID',axis=1)\n", + "\n", + "print(df_no_order_id.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\n", + "import numpy as np\n", + "\n", + "\n", + "df_no_order_id['Delivery_Time']=df_no_order_id['Delivery_Time'].fillna(np.mean(df['Delivery_Time']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df_no_order_id.duplicated().sum())\n", + "df_no_order_id = df_no_order_id.drop_duplicates()\n", + "print(df_no_order_id.describe())\n", + "print(df_no_order_id.info())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#4. **Encode categorical variables** if needed (Bonus if used One Hot Encoding)\n", + "object_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "LEncoder = LabelEncoder()\n", + "for col in object_cols:\n", + " df_no_order_id[col] = LEncoder.fit_transform(df_no_order_id[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#5. **Apply feature scaling for all features** (Use StandardScaler)\n", + "scaler = StandardScaler()\n", + "\n", + "features = ['Distance_km','Preparation_Time_min','Courier_Experience_yrs'] + object_cols\n", + "df_no_order_id[features] = scaler.fit_transform(df_no_order_id[features])\n", + "\n", + "df_clean = df_no_order_id.copy()\n", + "\n", + "print(df_clean.head())\n", + "print(df_clean.isnull().sum())\n", + "print(df_clean.shape)\n", + "df_clean = df_clean.dropna(axis=0)\n", + "\n", + "print(df_clean.isnull().sum())\n", + "print(df_clean.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#6. **Check for target imbalance and state if it is imbalanced or not** (keep this cell empty if not needed)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean[features].copy()\n", + "y = df_clean['Delivery_Time'].copy()" + ], + "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", + "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", + "'''\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "fold_losses = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "for fold, (train_index, val_index) in enumerate(kf.split(X)):\n", + " print(f'Fold {fold + 1}/{5}')\n", + " X_train_fold, X_val_fold = X.iloc[train_index], X.iloc[val_index]\n", + " y_train_fold, y_val_fold = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + " y_pred = model.predict(X_val_fold)\n", + " mae = mean_absolute_error(y_val_fold, y_pred)\n", + "\n", + " fold_losses.append(mae)\n", + "\n", + "average_losses = np.mean(fold_losses)\n", + "print(f\"MAE Average :{average_losses}\")\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': features,\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(fold_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MAE Loss')\n", + "plt.title('Linear Regression Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/316/Q2.ipynb b/submissions_extracted/316/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6d167880403402e8d25b34a71e1faea2f546572d --- /dev/null +++ b/submissions_extracted/316/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", + "\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 torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\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=True,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "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", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + " 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(input_dim,output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self,x):\n", + "\n", + " #L1\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " #L2\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #L3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " #Output\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + " 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", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch)\n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # TODO: Backward pass & optimization\n", + " # Step 1: Clear previous gradients\n", + " optimizer.zero_grad()\n", + " # Step 2: Compute gradients (backward pass)\n", + " loss.backward()\n", + " # Step 3: Update model parameters\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Calculate average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # Disable gradient computation using torch.no_grad()\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass - get model predictions\n", + " outputs = model(X_batch)\n", + "\n", + " # Compute loss using criterion\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "hidden_dim = 64\n", + "\n", + "output_dim = 1\n", + "\n", + "model = NN4Layer(hidden_dim=hidden_dim, input_dim=input_dim, output_dim=output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch 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:" + ], + "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/316/Q3.ipynb b/submissions_extracted/316/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..659d8a69c18a06177b239e5d9e9b902546330120 --- /dev/null +++ b/submissions_extracted/316/Q3.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "df_path = os.path.join(path,'Q3_data.csv')\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(df_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", + "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 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_values = (df.isnull().sum())\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_values.index,\n", + " 'missing_values': missing_values.values\n", + "})\n", + "missing_data = missing_data[missing_data['missing_values'] > 0].sort_values('missing_values', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "print(df[missing_data].head(20))\n", + "\n", + "df = df.dropna(axis=1)\n", + "\n", + "print(df.head)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.duplicated().sum())\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, MinMaxScaler\n", + "\n", + "print(df.select_dtypes('object').columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "num_cols = df.select_dtypes(include=['float64','int64']).columns\n", + "num_cols = num_cols.drop('Target')\n", + "scale = StandardScaler()\n", + "df_scaled = scale.fit_transform(df[num_cols])" + ], + "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_scaled[num_cols]\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "y = kf = KFold(n_split=5,shuffle=True, random_state=42)" + ], + "execution_count": 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/317/Q1.ipynb b/submissions_extracted/317/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5eac74612eab155e3a073c92211a573bbd6666ec --- /dev/null +++ b/submissions_extracted/317/Q1.ipynb @@ -0,0 +1,412 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import gdown\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": [ + "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", + "data = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(data['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": [ + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#data = data.drop(data[\"Order_ID\"])\n", + "#data = data.select_dtypes(include=[\"Order_ID\"]).columns.drop(\"Order_ID\")\n", + "#data = data.select_dtypes(include=[\"number\"]).columns\n", + "#data = data.drop(data[\"Order_ID\"])\n", + "data.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values per column:\")\n", + "print(data.isnull().sum())\n", + "print(f\"\\nTotal missing: {data.isnull().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "\n", + "# Drop rows with missing stat values\n", + "datac = data.dropna(subset=stat_cols).copy()\n", + "datac['Delivery_Time'] = datac['Delivery_Time'].fillna('none')\n", + "# or df['column_name'] = df['column_name'].fillna(df['column_name'].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values per column:\")\n", + "print(datac.isnull().sum())\n", + "print(f\"\\nTotal missing: {datac.isnull().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(f\"Duplicates: {datac.duplicated().sum()}\")\n", + "datac.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"after Duplicates: {datac.duplicated().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = datac.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " datac[col] = le.fit_transform(datac[col].astype(str))\n", + "datac.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "#encoder = OneHotEncoder(sparse_output=False)\n", + "#encoded = encoder.fit_transform(data[['column_name']])\n", + "#print(encoded)\n", + "#colors = [['Weather'], ['Traffic_Level'], ['Time_of_Day'], ['Vehicle_Type']]\n", + "\n", + "#encoder = OneHotEncoder(sparse_output=False)\n", + "#encoded = encoder.fit_transform(colors)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "datac.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Standardize features using StandardScaler\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = datac.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "datac[numerical_cols] = scaler.fit_transform(datac[numerical_cols])\n", + "datac.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(datac['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": [ + "datac.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "X = datac[feature_cols]\n", + "y = datac['Delivery_Time']\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)\n", + "#X = datac.drop(\"Delivery_Time\", axis=1)\n", + "#y = datac[\"Delivery_Time\"]\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "validation_error = mean_absolute_error(y_test, y_pred)\n", + "print(validation_error)\n", + "\n", + "# MSE Loss (Regression)\n", + "#mse_loss = nn.MSELoss()\n", + "#loss_mse = mse_loss(y_test, y_pred)\n", + "#print(\"MSE Loss:\", loss_mse.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.mean()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred.mean()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_test.mean()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# === [SEARCH TAG]: PLOT FEATURE IMPORTANCE ===\n", + "# Use after training tree-based model (RF, XGBoost, etc.)\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=True)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, 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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/317/Q2.ipynb b/submissions_extracted/317/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0c0acc8278b917fbdbd3905edeba26caf2e086b --- /dev/null +++ b/submissions_extracted/317/Q2.ipynb @@ -0,0 +1,532 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, Dataset\n", + "import torchvision\n", + "import torchvision.transforms as transforms\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Training dataset\n", + "train_dataset = CIFAR10(root='./q2-exam-data', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = CIFAR10(root='./q2-exam-data', 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": [ + "# 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": [ + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + "])" + ], + "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", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "# 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": [ + "# 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 2: Write your training loop here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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/317/Q3.ipynb b/submissions_extracted/317/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d0cdc67862c0f89218a12b530818daa805a8f07e --- /dev/null +++ b/submissions_extracted/317/Q3.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import gdown\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": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "data = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 2: Write your code here:\n", + "print(\"Missing values per column:\")\n", + "print(data.isnull().sum())\n", + "print(f\"\\nTotal missing: {data.isnull().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = data.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(f\"Duplicates: {data.duplicated().sum()}\")\n", + "data.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = data.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col].astype(str))\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Standardize features using StandardScaler\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "data[numerical_cols] = scaler.fit_transform(data[numerical_cols])\n", + "data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(data['Target'].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 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": [ + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "X = datac[feature_cols]\n", + "y = datac['Delivery_Time']\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)\n", + "#X = datac.drop(\"Delivery_Time\", axis=1)\n", + "#y = datac[\"Delivery_Time\"]\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# === [SEARCH TAG]: CATBOOST REGRESSOR ===\n", + "from catboost import CatBoostRegressor\n", + "model = CatBoostRegressor(n_estimators=100, max_depth=5, verbose=0)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predictions and metrics\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.describe()" + ], + "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", + "# === [SEARCH TAG]: PLOT FEATURE IMPORTANCE ===\n", + "# Use after training tree-based model (RF, XGBoost, etc.)\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=True)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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 Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/318/Q1.ipynb b/submissions_extracted/318/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..46171c9b9d271c7cc0a8b9ed0f1e6d2b5d89f861 --- /dev/null +++ b/submissions_extracted/318/Q1.ipynb @@ -0,0 +1,333 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "join_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(join_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", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Price')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# copy the dataset\n", + "df_clean = df.copy()\n", + "\n", + "\n", + "df_clean.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# dropna for rows with missing values\n", + "df_clean.dropna(inplace=True)\n", + "df_clean.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Shape before: {df.shape} \\nShape After: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df_clean.select_dtypes(include=[\"object\"]).columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "categorical = df_clean[['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']]\n", + "\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(categorical)\n", + "\n", + "print(encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_encoded = pd.DataFrame(encoded, columns=encoder.get_feature_names_out(categorical.columns))\n", + "categorical_encoded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_encoded['Distance_km'] = df_clean['Distance_km']\n", + "df_encoded = categorical_encoded.merge(df_clean.drop(columns=categorical))\n", + "df_encoded.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "# spliting the data before scaling to avoid data leakage\n", + "\n", + "X = df_encoded.drop(columns='Delivery_Time', axis=1)\n", + "y = df_encoded['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Unneeded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Done on cell 18" + ], + "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, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse\n", + "\n", + "# Using Kfold >> the target is a continous value\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mse_ls = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kfold.split(X)):\n", + "\n", + " X_train_scaled, X_test_scaled = 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_scaled, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test_scaled)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + "\n", + " # Store results\n", + " mse_ls.append(mse)\n", + "\n", + "print(sum(mse_ls)/len(mse_ls))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/318/Q2.ipynb b/submissions_extracted/318/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..14857d10401a3039ce8baca7573afb45ea622e45 --- /dev/null +++ b/submissions_extracted/318/Q2.ipynb @@ -0,0 +1,383 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "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, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "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", + "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", + "\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " 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", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\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", + "\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "import torch.nn.functional as F\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + "\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + "\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "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\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/318/Q3.ipynb b/submissions_extracted/318/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a4ce27f4995781d6fdc9e319f2223dbb961f939 --- /dev/null +++ b/submissions_extracted/318/Q3.ipynb @@ -0,0 +1,245 @@ +{ + "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", + "join_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(join_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.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.fillna(0, inplace=True)\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Not needed, features does not have any categorical values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "# spliting the data before scaling to avoid data leakage\n", + "\n", + "X = df.drop(columns='Target', axis=1)\n", + "y = df['Target']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "df['Target'].hist()\n", + "plt.show()\n", + "\n", + "# Imbalenced >> will use StratifiedKFold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Done on cell 10" + ], + "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", + "model = CatBoostClassifier(verbose=0, n_estimators=320, max_depth=4)\n", + "\n", + "lr_accuracy = []\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}/{5}\")\n", + "\n", + " X_train_scaled, X_test_scaled = 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_scaled, y_train)\n", + "\n", + " y_pred = model.predict(X_test_scaled)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + "\n", + "print(\"Accuracy:\", sum(lr_accuracy)/len(lr_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=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", + "golden = feature_importance['feature'][0]\n", + "golden" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/319/Q1.ipynb b/submissions_extracted/319/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d66196359197437981b3acaab7c8ff386c7c0b98 --- /dev/null +++ b/submissions_extracted/319/Q1.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "import kagglehub\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import seaborn as sns\n", + "from tqdm import tqdm\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", + "# reading the dataset\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", + "\n", + "# used the .head() to Inspect the first few rows used\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Display dataset information using\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Show statistical description\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Plot the target distribution (delivery_time)\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Drop the 'Order_ID' column from the data\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", + "#since we have to handle the missing values here is how :)\n", + "# Handle missing values appropriately\n", + "df_fill = df.fillna({'Weather': 'Unknown', 'age': 'Unknown','Time_of_Day': 'Unknown',\n", + " 'Courier_Experience_yrs': 0.0 })\n", + "print(\"\\n2. Fill with constant:\")\n", + "print(df_fill)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Checking if there is any duplicates\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "#Rule of thumb: removeding the dublicates:\n", + "df.drop_duplicates(inplace=True)\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "\n", + "colors = [['Order_ID'], ['Distance_km'], ['Weather'], ['Traffic_Level']\n", + " ,['Time_of_Day'], ['Vehicle_Type'], ['Preparation_Time_min'],\n", + " ['Courier_Experience_yrs'], ['Delivery_Time']]\n", + "\n", + "# using one-hot encoder:\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(colors)\n", + "\n", + "\n", + "print(\"Original:\", colors)\n", + "print(\"Encoded:\\n\", encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Apply feature scaling for all features\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # never scale the target\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\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": [ + "from numpy import float64\n", + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + " rf.fit(X_train, y_train)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('RandomForestRegressorn 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/319/Q2.ipynb b/submissions_extracted/319/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/319/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/319/Q3.ipynb b/submissions_extracted/319/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..385ddb4624235476a83a220ed73d79d46b4cc021 --- /dev/null +++ b/submissions_extracted/319/Q3.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from tqdm import tqdm\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 data\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# used the .head() to Inspect the first few rows used\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Display dataset information using\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Show statistical description\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#check missing data\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", + "# Checking if there is any duplicates\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "#Rule of thumb: removeding the dublicates:\n", + "df.drop_duplicates(inplace=True)\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 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "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\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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", + "#gonna use Stratified 5-Fold Cross-Validation, shuffled\n", + "\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", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Accuracy , losses, precision, recall , and F1 Score\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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/32/Q1.ipynb b/submissions_extracted/32/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4edc4b1219047243ac1a206024dc7a22020538a6 --- /dev/null +++ b/submissions_extracted/32/Q1.ipynb @@ -0,0 +1,297 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "#This part is to import all necessary libraries" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "df_clean = df.drop(columns=['Order_ID'])\n", + "df_clean.head(8)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n", + "check_missing_values(df_clean)\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": [ + "#The function above implies that duplicates must be omitted\n", + "df_clean.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\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 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 6: Write your code here:\n", + "#It is clearly evident from the target variable that there is no imbalance data in target variable and also because the target variable belongs to R which is the set of real numbers which is continuous." + ], + "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": [ + "print(\"Initializing models and K-Fold cross-validation...\")\n", + "\n", + "# Determine the number of classes for one-hot encoding\n", + "num_classes = len(np.unique(y))\n", + "\n", + "# 1. Initialize the machine learning models\n", + "models = {'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42)}\n", + "\n", + "# 2. Create a KFold object\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "\n", + "# 4. For each model:\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Convert y_val_fold (true labels) into a one-hot encoded format\n", + " y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n", + "\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + " loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n", + " fold_losses.append(loss)\n", + "\n", + " # Calculate the average loss for the model\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/32/Q2.ipynb b/submissions_extracted/32/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..60118ba8761eac01af21b7cc69041e2e72e2b199 --- /dev/null +++ b/submissions_extracted/32/Q2.ipynb @@ -0,0 +1,224 @@ +{ + "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\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", + "train_dataset = X_train, y_train\n", + "test_dataset = X_test, y_test\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": [ + "# 2. Create TensorDataset objects\n", + "#It is abover their" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "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", + "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/32/Q3.ipynb b/submissions_extracted/32/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d69842c7179cb171dc98a2dea96171bc25e9620 --- /dev/null +++ b/submissions_extracted/32/Q3.ipynb @@ -0,0 +1,212 @@ +{ + "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", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import os\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", + "new_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(new_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136']\n", + "df = df.dropna(subset=['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", + "# 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", + "#There is no need to encode categorical variables since all variables are numerical" + ], + "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.columns) # 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:" + ], + "execution_count": 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/320/Q1.ipynb b/submissions_extracted/320/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..363f45da2b561774414ced3bca7470b2037ad8bf --- /dev/null +++ b/submissions_extracted/320/Q1.ipynb @@ -0,0 +1,482 @@ +{ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('time Distribution')\n", + "plt.xlabel('time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns= 'Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# for check\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Delivery_Time' , 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\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": [ + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Define features and target\n", + "feature_cols = stat_cols + ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# TODO: Split data with stratification (test_size=0.2, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Scale features using StandardScaler\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": [ + "\n", + "###### كود اضافي لتاسك 5\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "target_col_name = 'Target'\n", + "\n", + "if target_col_name in df.columns:\n", + " numerical_features = df.drop(columns=[target_col_name]).select_dtypes(include=['number']).columns\n", + " print(f\"Excluding target column '{target_col_name}' from scaling.\")\n", + "else:\n", + " numerical_features = df.select_dtypes(include=['number']).columns\n", + " print(f\"Warning: Target column '{target_col_name}' not found. All numerical columns are being scaled.\")\n", + " print(\"If your target column has a different name, please replace 'target' in the code above.\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_features] = scaler.fit_transform(df[numerical_features])\n", + "print(\"Numerical features scaled using StandardScaler.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df['Delivery_Time'].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "model = {\n", + "\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "\n", + "}\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in model:\n", + " all_results[name] = {'mse': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "### this is for feature importance from your trained model ( Ridge & LASSO)\n", + "\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = model['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "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": [ + "feature_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "importance_series = pd.Series(feature_importances, index=feature_names)\n", + "importance_series = importance_series.sort_values(ascending=False)\n", + "\n", + "print(\"Feature Importances :\\n\")\n", + "print(importance_series.head(10))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "\n", + "target_column_name = 'Target'\n", + "\n", + "\n", + "if target_column_name not in df.columns:\n", + " raise ValueError(f\"Target column '{target_column_name}' not found in t\")\n", + "\n", + "X = df.drop(columns=[target_column_name])\n", + "y = df[target_column_name]\n", + "\n", + "print(\"Dataset split into target (y).\")\n", + "print(f\"X shape: {X.shape}\")\n", + "print(f\"y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "\n", + "target_column_name = 'Target' # Corrected from 'target' to 'Target'\n", + "\n", + "# Check if the target column exists\n", + "if target_column_name not in df.columns:\n", + " raise ValueError(f\"Target column '{target_column_name}' not found in the DataFrame. Please check the column name.\")\n", + "\n", + "X = df.drop(columns=[target_column_name])\n", + "y = df[target_column_name]\n", + "\n", + "print(\"Dataset split into features (X) and target (y).\")\n", + "print(f\"X shape: {X.shape}\")\n", + "print(f\"y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/320/Q2.ipynb b/submissions_extracted/320/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b1f031a6dc13ab0c30e5d93b03aa8a31494293e4 --- /dev/null +++ b/submissions_extracted/320/Q2.ipynb @@ -0,0 +1,495 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub # for importing the dataset\n", + "import pandas as pd # dataframe stuff\n", + "import numpy as np # in general, it's a mathematical library\n", + "import torch # admin this lab\n", + "import torch.nn as nn # for building the model\n", + "from torch.optim import AdamW # optimizer\n", + "import matplotlib.pyplot as plt # visualizing\n", + "from torch.utils.data import 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()}\") # checking for GPU" + ], + "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": [ + "\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", + "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).unsqueeze(1) # Add a dimension for regression target\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1) # Add a dimension for regression target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "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", + "\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": [], + "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", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# another code for display sample images (اسهل هذا الكود من الي باللاب بالطباعه)\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + "\n", + " img = data_batch[i].permute(1, 2, 0).numpy()\n", + " age = labels_batch[i].item()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {int(age)}\")\n", + " axes[i].axis('off')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # 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", + " a3 = self.layer3(a2)\n", + "\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\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", + " #(32,) → (32, 1) if we dont change we couldnt calculate the loss\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "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\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (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", + "# 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/320/Q3.ipynb b/submissions_extracted/320/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..95f716b13d57b041833bec8a4fb311fa459428a2 --- /dev/null +++ b/submissions_extracted/320/Q3.ipynb @@ -0,0 +1,405 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub # for importing the dataset\n", + "import pandas as pd # dataframe stuff\n", + "import numpy as np # in general, it's a mathematical library\n", + "import torch # admin this lab\n", + "import torch.nn as nn # for building the model\n", + "from torch.optim import AdamW # optimizer\n", + "import matplotlib.pyplot as plt # visualizing\n", + "from torch.utils.data import 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()}\") # checking for GPU" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import pandas as pd\n", + "\n", + "data_path = f\"{path}/Q3_data.csv\"\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Do we have missing values?\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n" + ], + "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", + "\n", + "#Standardize features using StandardScaler (DON'T scale the target!)\n", + "\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# Apply fit_transform to scale the numerical columns\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Apply feature scaling to numerical features\n", + "\n", + "target_column_name = 'Target'\n", + "\n", + "if target_column_name in df.columns:\n", + " numerical_features = df.drop(columns=[target_column_name]).select_dtypes(include=['number']).columns\n", + " print(f\"Excluding target column '{target_column_name}' from scaling.\")\n", + "else:\n", + " numerical_features = df.select_dtypes(include=['number']).columns\n", + " print(f\"Warning: Target column '{target_column_name}' not found. All numerical columns are being scaled.\")\n", + " print(\"If your target column has a different name, please replace 'target' in the code above.\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_features] = scaler.fit_transform(df[numerical_features])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target_column_name = 'Target'\n", + "\n", + "# Check if the target column exists\n", + "if target_column_name not in df.columns:\n", + " raise ValueError(f\"Target column '{target_column_name}' not found in the DataFrame. Please check the column name.\")\n", + "\n", + "X = df.drop(columns=[target_column_name])\n", + "y = df[target_column_name]\n", + "\n", + "print(\"Dataset split into features (X) and target (y).\")\n", + "print(f\"X shape: {X.shape}\")\n", + "print(f\"y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "n_splits = 5 # K\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "# Train a CatBoostClassifier model\n", + "sklearn_model = {\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + " }" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "##### برجع له لاني لخبطت فيه\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# Check for target imbalance\n", + "print(\"\\nTarget distribution:\")\n", + "print(y.value_counts(normalize=True))\n", + "\n", + "if y.value_counts(normalize=True).min() < 0.2:\n", + " print(\"Target is imbalanced, using StratifiedKFold.\")\n", + " kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + " metric_to_use = 'f1_score'\n", + "else:\n", + " print(\"Target is balanced, using KFold.\")\n", + " kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + " metric_to_use = 'accuracy'\n", + "\n", + "# Initialize lists to store scores\n", + "fold_scores = []\n", + "\n", + "# Train the CatBoostClassifier model with cross-validation\n", + "print(f\"\\nTraining CatBoostClassifier with {kf.n_splits}-fold {type(kf).__name__}...\")\n", + "\n", + "for fold, (train_index, val_index) in enumerate(kf.split(X, y)):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model = CatBoostClassifier(\n", + " iterations=1000,\n", + " learning_rate=0.05,\n", + " depth=6,\n", + " l2_leaf_reg=3,\n", + " loss_function='Logloss',\n", + " eval_metric='F1' if metric_to_use == 'f1_score' else 'Accuracy',\n", + " random_seed=42,\n", + " verbose=0,\n", + " early_stopping_rounds=50\n", + " )\n", + "\n", + " model.fit(X_train, y_train, eval_set=(X_val, y_val), early_stopping_rounds=50, verbose=0)\n", + "\n", + " y_pred = model.predict(X_val)\n", + "\n", + " if metric_to_use == 'f1_score':\n", + " score = f1_score(y_val, y_pred)\n", + " else:\n", + " score = model.get_best_score()['validation']['Accuracy']\n", + "\n", + " fold_scores.append(score)\n", + " print(f\"Fold {fold+1} {metric_to_use}: {score:.4f}\")\n", + "\n", + "# Print the averaged score\n", + "average_score = np.mean(fold_scores)\n", + "print(f\"\\nAverage {metric_to_use} across all folds: {average_score:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "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/321/Q1.ipynb b/submissions_extracted/321/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f838736089283c48f060d234b8e0b32d11b9990d --- /dev/null +++ b/submissions_extracted/321/Q1.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "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", + "\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", + "# 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=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food = df_food.drop(columns=['Order_ID']).copy()\n", + "print(f\"Shape after cleaning: {df_food.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_food.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Select relevant columns,\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "\n", + "# Drop rows where target or key features are missing - can't predict without them\n", + "print(f\"Before: {df_food.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Time_of_Day', 'Traffic_Level', 'Delivery_Time' ,'Courier_Experience_yrs'])\n", + "print(f\"After dropping missing value: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' since can predict without it\n", + "df_clean['Weather'] = df_clean['Weather'].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Do we have categorical columns?\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": [ + "# Encode Categorical Features\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in df_clean.select_dtypes(include=[\"object\"]).columns:\n", + " df_clean[col] = label_encoder.fit_transform(df_clean[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")\n", + "#Dataset imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "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": [ + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "\n" + ], + "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", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "\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": [ + "# Gather importances from the models (from the last fold)\n", + "\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_fold_pred, bins=50, edgecolor='black', color='green')\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/321/Q2.ipynb b/submissions_extracted/321/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f2ea2653ee13357c57090dcb8ae30b811e6fe024 --- /dev/null +++ b/submissions_extracted/321/Q2.ipynb @@ -0,0 +1,436 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "# transform to tensors BCELoss\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", + "# 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 30 feature\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# 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", + "print(f\"Training batch input shape: {X_batch[0].shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + "# Second hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\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": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/321/Q3.ipynb b/submissions_extracted/321/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..511409e9029edd60ce569b0f5b05234d5611680d --- /dev/null +++ b/submissions_extracted/321/Q3.ipynb @@ -0,0 +1,404 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the CSV file\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", + "\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", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_q3.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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_q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values\n", + "missing_percentage = (df_q3.isnull().sum() / len(df_q3)) * 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": [ + "# Drop rows with missing stat values\n", + "stat_cols =missing_data['Column']\n", + "df_clean = df_q3.dropna(subset=stat_cols).copy()" + ], + "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_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have categorical columns?\n", + "categorical_cols = df_q3.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#we do not have" + ], + "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_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1- Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Target\")\n", + "#2- Target distribution\n", + "print(f\"Legendary: {df_clean['Target'].sum()}\")\n", + "print(f\"Normal: {(df_clean['Target'] == 0).sum()}\")\n", + "# DATASET imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Target\", axis=1).astype(float)\n", + "y = df_clean['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/322/Q1.ipynb b/submissions_extracted/322/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4bf72d8a5a3face32cfe1033f1369f5c83759ca2 --- /dev/null +++ b/submissions_extracted/322/Q1.ipynb @@ -0,0 +1,287 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import matplotlib.pyplot as plt\n", + "\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", + "\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(path + \"/Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "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": [ + "plt.hist(df[\"Delivery_Time\"], bins=20)\n", + "plt.xlabel(\"Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Delivery Time Distribution\")\n", + "plt.show()" + ], + "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": [ + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y = df[\"Delivery_Time\"]\n", + "\n", + "if y.nunique() <= 10:\n", + " counts = y.value_counts()\n", + " ratio = counts.min() / counts.max()\n", + "\n", + " print(\"Classification target\")\n", + " print(\"Class counts:\\n\", counts)\n", + " print(\"Imbalance ratio:\", round(ratio, 2))\n", + "else:\n", + " print(\"Regression target\")\n", + " print(y.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "X = df.drop(columns=[\"Delivery_time\"])\n", + "y = df[\"Delivery_time\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: CV split + Train RandomForest + Evaluate using MAE + Print average MAE\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "if y.nunique() <= 10:\n", + " cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X, y)\n", + "else:\n", + " cv = KFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in splits:\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 = RandomForestRegressor(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(\"MAE scores per fold:\", np.round(mae_scores, 3))\n", + "print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "feature_importance = pd.Series(\n", + " model.feature_importances_, index=X.columns\n", + ").sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(8,4))\n", + "feature_importance.plot(kind=\"bar\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importance\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = model.predict(X)\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(y_pred, bins=20)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train, X_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 = 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", + " pred_rf = rf.predict(X_test)\n", + " pred_cb = cb.predict(X_test)\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, pred_avg)\n", + " mae_scores.append(mae)\n", + "\n", + "print(\"MAE per fold:\", np.round(mae_scores, 3))\n", + "print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/322/Q2.ipynb b/submissions_extracted/322/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1a690398b0b8c5a1c1ab0abac05ef2e575fb7e6 --- /dev/null +++ b/submissions_extracted/322/Q2.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/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, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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(\"Images batch shape:\", images_batch.shape)\n", + "print(\"Ages batch shape:\", ages_batch.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(8,4))\n", + "\n", + "for i in range(6):\n", + " img = images_batch[i].permute(1, 2, 0) # Convert from (C, H, W) to (H, W, C)\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {ages_batch[i].item()}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "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 AgeMLP(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgeMLP, self).__init__()\n", + " self.net = nn.Sequential(\n", + " nn.Linear(input_size, 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + "\n", + " for X_batch, y_batch in loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).float().view(-1, 1)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(X_batch)\n", + " loss = criterion(preds, y_batch)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).float().view(-1, 1)\n", + "\n", + " preds = model(X_batch)\n", + " loss = criterion(preds, y_batch)\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "sample_X, _ = next(iter(train_loader))\n", + "input_size = sample_X[0].numel()\n", + "\n", + "model = AgeMLP(input_size).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "\n", + "epochs = 20\n", + "for epoch in range(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}/{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.plot(train_losses, label=\"Train 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\")\n", + "plt.legend()\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/322/Q3.ipynb b/submissions_extracted/322/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e7c0bd438c97aa5c13f6a14fd4adf8f80800aa86 --- /dev/null +++ b/submissions_extracted/322/Q3.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "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": [ + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "target_col = df.columns[-1]\n", + "\n", + "missing = df.isnull().sum()\n", + "print(\"Columns with missing values:\\n\", missing[missing > 0])\n", + "\n", + "num_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\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": [ + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "if len(cat_cols) > 0:\n", + " df = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "counts = y.value_counts()\n", + "ratio = counts.min() / counts.max()\n", + "print(\"Target counts:\\n\", counts)\n", + "print(\"Minority/Majority ratio:\", round(ratio, 3))\n", + "print(\"Imbalanced:\", \"Yes\" if ratio < 0.5 else \"No\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import GradientBoostingClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "# Note: Keeps class distribution in each fold.\n", + "\n", + "scores = []\n", + "use_f1 = (y.value_counts().min() / y.value_counts().max()) < 0.5\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 = GradientBoostingClassifier(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " # Note: Model is trained on each fold.\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " if use_f1:\n", + " score = f1_score(y_test, y_pred)\n", + " metric_name = \"F1\"\n", + " # Note: F1 is used when data is imbalanced.\n", + " else:\n", + " score = accuracy_score(y_test, y_pred)\n", + " metric_name = \"Accuracy\"\n", + " # Note: Accuracy is used when classes are balanced.\n", + "\n", + " scores.append(score)\n", + "\n", + "# Task 5: Print average score\n", + "print(f\"{metric_name} per fold:\", np.round(scores, 3))\n", + "print(f\"Average {metric_name}:\", round(np.mean(scores), 3))\n", + "# Note: Final score is averaged across 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/323/Q1.ipynb b/submissions_extracted/323/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..06297e16e1aa074f77345ae614b3330c2130bff0 --- /dev/null +++ b/submissions_extracted/323/Q1.ipynb @@ -0,0 +1,420 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "!pip install catboost\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from catboost import CatBoostRegressor\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", + "\n", + "# We basically read the path of the csv path with the respected csv name, then we read the data and store it into df -> Pandas DataFrame format for csv files\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Here we simply just use the .head() function to read the first 5 rows of the Dataset\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Here we use the info() function to give us a clear summary of the dataset\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Here we show the statistical insights of the given dataset\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Here we first extract the values of the Target variable (Delivery_Time) and then we plot the distribution of it with a proper number of bins\n", + "\n", + "deliv_time = df['Delivery_Time']\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(deliv_time, bins=20, edgecolor='black')\n", + "plt.xlabel(\"Values\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n", + "\n", + "# INSIGHTS!\n", + "# As we can see from the distribution of the data, it's following a Normal Distribution or a Gaussian Distribution which is generally good :D" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Here we basically drop the Order_ID column and show the first 5 rows as a confirmation for the deletion\n", + "\n", + "df = df.drop(\"Order_ID\", axis = 1)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Here we will perform a comperhensive Missing Values investigation properly and then handle them\n", + "\n", + "# General information\n", + "print(\"Dataset Information:\")\n", + "df.info()\n", + "\n", + "# Missing values per column\n", + "print(\"\\nMissing values per column:\")\n", + "print(df.isna().sum())\n", + "\n", + "# Total missing values in dataset\n", + "print(\"\\nTotal missing values in dataset:\")\n", + "print(df.isna().sum().sum())\n", + "\n", + "# Percentage of missing values per column\n", + "print(\"\\nPercentage of missing values per column:\")\n", + "print(df.isna().mean() * 100)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Now after we checked the Number of missing values\n", + "# We identified the Categorical Columns from Numerical Columns\n", + "# We handle Missing Values appropiatley\n", + "# Categorical Columns filled with .mode()\n", + "# Numerical Columns filled with .median()\n", + "\n", + "categ_miss_cols = [\"Weather\",\"Traffic_Level\",\"Time_of_Day\"]\n", + "num_miss_cols = [\"Courier_Experience_yrs\",\t\"Delivery_Time\"]\n", + "\n", + "for col in categ_miss_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "for col in num_miss_cols:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "# Now we check the number of missing values after filling\n", + "print(f\" Number of Missing Values in the df: {df.isna().sum().sum()}\")\n", + "\n", + "# GOOD!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "\n", + "# Here we will check the number of duplicates in the dataset\n", + "print(f\"Number of Duplicates Before Cleaning: {df.duplicated().sum()}\")\n", + "\n", + "# Now we will Drop them And Check after that the number of duplicates\n", + "df = df.drop_duplicates()\n", + "\n", + "print(f\"Number of Duplicates After Cleaning: {df.duplicated().sum()}\")\n", + "\n", + "# Everything Looks Good!" + ], + "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", + "\n", + "categ_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "print(f\"Categorical columns in the Dataset: {categ_cols}\")\n", + "# After inspecting the Data Looks like We need to use LabelEncoder() Because the Ordering of the categorical column values, we do NOT USE OneHotEncoder, I JUST TRIED IT AND GOT AN ERROR!\n", + "\n", + "for col in categ_cols:\n", + " encoder = LabelEncoder()\n", + " df[col] = encoder.fit_transform(df[col].astype(str))\n", + "\n", + "# Now ew just Check the Categorical Columns in the Dataset After Encoding them\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "# Here we simply define the StandardScaler function from Sklearn and apply it to the whole dataset features\n", + "# BUT!!, Before that we need to extract all the feature names and Scale so we would be having a DataFrame at the End not a Numpy Array ! (df = sacler.fit_transform(df) -> Results into Numpy Array!)\n", + "# REMEMBER WE DONT SCALE THE TARGET AT ALL!\n", + "\n", + "columns = df.columns.drop(\"Delivery_Time\").tolist()\n", + "print(f\"DataFrame Features: {columns}\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "df[columns] = scaler.fit_transform(df[columns])\n", + "\n", + "# We Just check the Values now\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "\n", + "# WE DONT NEED TO CHECK THE CLASS IMBALANCE SINCE THE TARGET IS CONTINOUS AND NOT CATEGORICAL!!!" + ], + "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", + "\n", + "# Basically Assign the right Features to X and y\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Here we First Define the KFold Function from sklearn, Then we define Our Model and then Training Loop of the Folds, Finally Print out the Metrics\n", + "# ALL LIBRARIES ARE IMPORTED IN THE FIRST CELL\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kfold.split(X), start=1):\n", + " print(f\"Fold Number: {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 and predict\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "# Here we first extract the Feature Cols (DO NOT INCLUDE THE TARGET!)\n", + "feature_cols = df.columns.drop(\"Delivery_Time\").tolist()\n", + "\n", + "# Then Group the Feature Cols with it's importance from the model respectivly and plt the Feature importance plot\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'], edgecolor='black')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Simply Just plot the distribution of the predicited values\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=20, edgecolor=\"black\")\n", + "plt.title(\"Predicted Delivery Time Histogram\")\n", + "plt.xlabel(\"Distribution\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n", + "\n", + "# Gaussian Distribution Predictions :D" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "# First we Define Our Models\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "# Simply Define a Dicitionary to Store the Model/Results(MAEs)\n", + "\n", + "RFR_preds = []\n", + "Cat_preds = []\n", + "\n", + "all_results = {}\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "# LOOP THROUGH THE MODELS\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", + " if model_name == \"Random Forest Regressor\":\n", + " RFR_preds.append(y_pred)\n", + " else:\n", + " Cat_preds.append(y_pred)\n", + "\n", + "# Just to access the Values\n", + "RFR_preds = RFR_preds[0]\n", + "Cat_preds = Cat_preds[0]\n", + "\n", + "# Now we have collected All Models Predictions, We Basically Average them Out and Calculate the MAE\n", + "print(50 * \"==\")\n", + "ensemble_preds = 0.5 * RFR_preds + 0.5 * Cat_preds\n", + "print(f\"Ensembled Predictions: {ensemble_preds}\")\n", + "print(50 * \"==\")\n", + "print(f\"MAE: {mean_absolute_error(y_test, ensemble_preds)}\")" + ], + "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/323/Q2.ipynb b/submissions_extracted/323/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e38efceb4030d7898534d3b9d0bd4dad5485ef00 --- /dev/null +++ b/submissions_extracted/323/Q2.ipynb @@ -0,0 +1,452 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "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", + "# Basically Just transform it as we can see into float32 :D\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", + "# Simply Group the Training and Testing data to their proper TensorDataset\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", + "# Simply Create Data Loaders With the specified batch sizes for both Training/Testing TensorDatasets\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=True,\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Simply Printout The Data Sizes Along their Batch sizes\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "print(20*\"--\")\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", + "print(20*\"--\")\n", + "X_batch, y_batch = next(iter(test_loader))\n", + "print(f\"Testing batch input shape: {X_batch.shape}\")\n", + "print(f\"Testing batch labels shape: {y_batch.shape}\")\n", + "# Important Note: (Data Shape is Correct! and contains 32 batches, 3 channels with 36*36 of highet and width)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Here we Randomly Sample from the training data and show some images as shown below\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", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> Prediction\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # make predictions\n", + " outputs = model(X_batch)\n", + " # compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\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)\n", + " y_batch = y_batch.to(device)\n", + " # Forward pass\n", + " # make predictions\n", + " outputs = model(X_batch)\n", + " # compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# What are input features ?\n", + "# 32, 3, 36, 36\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "# choose number of hidden neurons\n", + "hidden_dim = 16\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Number of epochs\n", + "num_epochs = 20\n", + "\n", + "\n", + "# learning rate\n", + "learning_rate = .1\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "\n", + "# TODO: Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "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\"Predicted: {labels[i].item()}\")\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/323/Q3.ipynb b/submissions_extracted/323/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a7c2e5e3f03600216dd701a19b4c8fd9f8640e5 --- /dev/null +++ b/submissions_extracted/323/Q3.ipynb @@ -0,0 +1,405 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install catboost\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "\n", + "# Simply Join the Path with the appropiate csv name\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", + "\n", + "# Here we read the first 5 rows using the head() function\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# here we display General information about data\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# And here we show the Statistical Information of the data\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# General information\n", + "print(\"Dataset Information:\")\n", + "df.info()\n", + "\n", + "# Missing values per column\n", + "print(\"\\nMissing values per column:\")\n", + "print(df.isna().sum())\n", + "\n", + "# Total missing values in dataset\n", + "print(\"\\nTotal missing values in dataset:\")\n", + "print(df.isna().sum().sum())\n", + "\n", + "# Percentage of missing values per column\n", + "print(\"\\nPercentage of missing values per column:\")\n", + "print(df.isna().mean() * 100)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# So as we can see from the previous cell, there are a lot of Missing values across the dataset\n", + "# And since all features are numerica/continous we may use the Median to fill missing values (We won't use the mean since it's sensitive to Outliers!)\n", + "\n", + "features = df.columns.tolist()\n", + "\n", + "for feature in features:\n", + " df[feature] = df[feature].fillna(df[feature].median())\n", + "\n", + "# Now we check the number of missing values\n", + "\n", + "print(f\"Number of MIssing Values After Cleaning: {df.isna().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Here we will check the number of duplicates in the dataset\n", + "print(f\"Number of Duplicates in the Dataset: {df.duplicated().sum()}\")\n", + "\n", + "# Looks Like there's No Duplicates!! ALL GOOD ! :D" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "categ_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "print(f\"Categorical Columns we have in the Dataset: {categ_cols}\")\n", + "\n", + "# The List is Empty!! Therefore there are no Categorical Columns!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "\n", + "# Now we simply extract the feature names and then Drop the Target Column !! WE DONT TRANSFORM THE TARGET COLUMN!\n", + "# then we apply a standard scaler to the data\n", + "columns = df.columns.drop(\"Target\").tolist()\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "df[columns] = scaler.fit_transform(df[columns])\n", + "\n", + "# We Just check the Values now\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Class distribution\n", + "target = df[\"Target\"].value_counts()\n", + "\n", + "print(\"Class distribution (counts):\")\n", + "print(target)\n", + "\n", + "print(\"\\nClass distribution (percentages):\")\n", + "print(target / target.sum() * 100)\n", + "\n", + "# Visualization\n", + "plt.figure(figsize=(8, 4))\n", + "plt.bar(target.index.astype(str), target.values, edgecolor='Black')\n", + "plt.title(\"Class Distribution of targetendary\")\n", + "plt.xlabel(\"Class Label\")\n", + "plt.ylabel(\"Count\")\n", + "plt.show()\n", + "\n", + "# There's a clear class imbalance ratio!!\n", + "# As we can see Labels of Class 0 are: 14732\n", + "# While Labels of Class 1 are: 5269\n", + "\n", + "# With a Clear Class Imbalance Ratio of:\n", + "#0 73.6%\n", + "#1 26.4%\n", + "\n", + "# Take a look into the plot too!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n", + "\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + " X_fold_train, X_fold_val = X.iloc[train_index], X.iloc[test_index]\n", + " y_fold_train, y_fold_val = y.iloc[train_index], y.iloc[test_index]\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", + " accuracy_scores.append(accuracy_score(y_fold_val, y_fold_pred))\n", + " f1_scores.append(np.sqrt(f1_score(y_fold_val, y_fold_pred)))\n", + "\n", + "accuracy_scores = np.array(accuracy_scores)\n", + "f1_scores = np.array(f1_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"Accuracy: {accuracy_scores.mean():,.2f}%\")\n", + "print(f\"F1-Score: {f1_scores.mean():,.2f}%\")" + ], + "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", + "\n", + "# Here we first extract the Feature Cols (DO NOT INCLUDE THE TARGET!)\n", + "feature_cols = df.columns.drop(\"Target\").tolist()\n", + "\n", + "# Then Group the Feature Cols with it's importance from the model respectivly and plt the Feature importance plot\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'], edgecolor='black')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n", + "\n", + "# As we can see here we plotted all Feature Importances!, WE CANT LOOK AT IT! SO LETS JUST GET THE TOP 5 HERE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_importance = feature_importance.head()\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'], edgecolor='black')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n", + "\n", + "# Now it Looks Good!, And the Golden Feature is the P_2 !!!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Since Our feature_importance dataframe has the features ordered based on the importance, we could just select the first index !, because it contains the feature with most importance\n", + "feature_importance.iloc[0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "X = df['P_2']\n", + "y = df['Target']\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + " X_fold_train, X_fold_val = X.iloc[train_index], X.iloc[test_index]\n", + " y_fold_train, y_fold_val = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " print(X_fold_train.shape)\n", + " print(X_fold_val.shape)\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + " print(y_fold_pred.shape)\n", + " print(y_fold_val.shape)\n", + "\n", + " # Calculate metrics\n", + " accuracy_scores.append(accuracy_score(y_fold_val, y_fold_pred))\n", + " f1_scores.append(np.sqrt(f1_score(y_fold_val, y_fold_pred)))\n", + "\n", + "accuracy_scores = np.array(accuracy_scores)\n", + "f1_scores = np.array(f1_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"Accuracy: {accuracy_scores.mean():,.2f}%\")\n", + "print(f\"F1-Score: {f1_scores.mean():,.2f}%\")\n", + "\n", + "\n", + "# After printing Out the Shapes and trying to debug, i don't know what is the y_fold_pred is 0\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/324/Q1.ipynb b/submissions_extracted/324/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e17ac77f77938c6cdf0ce031e426b2c9b6157c0f --- /dev/null +++ b/submissions_extracted/324/Q1.ipynb @@ -0,0 +1,239 @@ +{ + "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", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\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": [ + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "# 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": [ + "df_cleaned = df.drop(columns = 'Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_cleaned['Weather'] = df_cleaned['Weather'].fillna(df_cleaned['Weather'].mode()[0]) #fill the categorical columns with mode\n", + "df_cleaned['Traffic_Level'] = df_cleaned['Traffic_Level'].fillna(df_cleaned['Traffic_Level'].mode()[0])\n", + "df_cleaned['Time_of_Day'] = df_cleaned['Time_of_Day'].fillna(df_cleaned['Time_of_Day'].mode()[0])\n", + "\n", + "df_cleaned['Courier_Experience_yrs'] = df_cleaned['Courier_Experience_yrs'].fillna(df_cleaned['Courier_Experience_yrs'].mean()) #fill the numerical columns with mean\n", + "df_cleaned['Delivery_Time'] = df_cleaned['Delivery_Time'].fillna(df_cleaned['Delivery_Time'].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df_cleaned.duplicated().sum() # sum of all duplicated rows\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows.\")\n", + " df_cleaned.drop_duplicates(inplace=True) #drop the duplicated rows\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "le = LabelEncoder()\n", + "df_cleaned['Weather'] = le.fit_transform(df_cleaned['Weather'])\n", + "df_cleaned['Traffic_Level'] = le.fit_transform(df_cleaned['Traffic_Level'])\n", + "df_cleaned['Time_of_Day'] = le.fit_transform(df_cleaned['Time_of_Day'])\n", + "df_cleaned['Vehicle_Type'] = le.fit_transform(df_cleaned['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "df_cleaned[['Distance_km', 'Weather', 'Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min', 'Courier_Experience_yrs']] = scaler.fit_transform(df_cleaned[['Distance_km', 'Weather', 'Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min', 'Courier_Experience_yrs']]) #scaling all without Target\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_cleaned.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "X = df_cleaned[feature_cols]\n", + "y = df_cleaned['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: {mae:,.2f}\")" + ], + "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/324/Q2.ipynb b/submissions_extracted/324/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe19ef49bc1ee7c43f64c19ad34720cdc5ea9dcb --- /dev/null +++ b/submissions_extracted/324/Q2.ipynb @@ -0,0 +1,348 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "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}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "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", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a2)\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.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": [ + "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": [ + "input_dim = X_train.shape[1]\n", + "hidden_dim = 5\n", + "learning_rate = 0.001\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "criterion = nn.MSELoss()\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(20):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{20}], '\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": [ + "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/324/Q3.ipynb b/submissions_extracted/324/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c5c7fb8f3e55baef2731d49c528277111a2c1658 --- /dev/null +++ b/submissions_extracted/324/Q3.ipynb @@ -0,0 +1,237 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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(df.isnull().sum()) #Check missing values\n", + "for col in df.columns:\n", + " df[col] = df[col].fillna(df[col].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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) # inplace = True to make the changes to the same DataFrame\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: floats and ints values, no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "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": [ + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importance = 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/325/Q1.ipynb b/submissions_extracted/325/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e185461eec6857d69c9dba594ae91e810ab6590 --- /dev/null +++ b/submissions_extracted/325/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": [ + "#Import Libraries\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#read Data\n", + "Data = pd.read_csv(\"/content/Q1_data.csv\")\n", + "Data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "#Print head\n", + "Data = pd.read_csv(\"/content/Q1_data.csv\")\n", + "Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Check data types and structure\n", + "Data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Descriptive statistics for numerical columns\n", + "Data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot Delivery Time\n", + "condition_counts = Data['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('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", + "#Drop Order ID\n", + "Data = Data.drop(\"Order_ID\",axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#check missing value\n", + "print(Data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Handle missing values\n", + "# we have Weather, Traffic_Level, Time_of_Day, Courier_Experience_yrs and Delivery_Time have null\n", + "Data = Data.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#check duplicated value\n", + "Data.duplicated().sum()\n", + "\n", + "# drop duplicated\n", + "Data = Data.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode variables by OneHotEncoder\n", + "print('data before encoding:\\n', Data) # before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(Data)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) # after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# feature scaling by StandardScaler\n", + "numerical_cols = Data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # else target\n", + "\n", + "scaler = StandardScaler()\n", + "Data[numerical_cols] = scaler.fit_transform(Data[numerical_cols])\n", + "Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# Check target imbalance\n", + "target_dist = y.value_counts(normalize=True)\n", + "print(target_dist)\n", + "\n", + "if target_dist.max() > 0.6:\n", + " print(\"The target variable is imbalanced.\")\n", + "else:\n", + " print(\"The target variable is balanced.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "np.random.seed(42)\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio 80% train, 20% test\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2,\n", + " random_state=42,\n", + " shuffle=True,\n", + " stratify=y\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "# K-Fold\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task 3\n", + "# we need to train scaler\n", + "for tr_idx, va_idx in kf.split(X):\n", + " X_tr, X_va = X.iloc[tr_idx], X.iloc[va_idx]\n", + " y_tr, y_va = y.iloc[tr_idx], y.iloc[va_idx]\n", + "\n", + " model = RandomForestRegressor(\n", + " n_estimators=200,\n", + " max_depth=None,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " model.fit(X_tr, y_tr)\n", + " y_pred = model.predict(X_va)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mae_scores.append(mean_absolute_error(y_va, y_pred))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task 5\n", + "print(\"Average MAE across folds:\", np.mean(mae_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "\n", + "importances = model.feature_importances_\n", + "indices = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.bar(range(len(importances)), importances[indices])\n", + "plt.xticks(range(len(importances)), X_train.columns[indices], rotation=90)\n", + "plt.xlabel(\"Features\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importance from Random Forest Model\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Predict delivery time\n", + "y_pred = model.predict(X_test)\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Histogram of Predicted Delivery Time\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# need to install\n", + "!pip install catboost\n", + "\n", + "X_np = X.values if hasattr(X, \"values\") else X\n", + "y_np = y.values if hasattr(y, \"values\") else y\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "fold_maes = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X_np), start=1):\n", + " X_train, X_val = X_np[train_idx], X_np[val_idx]\n", + " y_train, y_val = y_np[train_idx], y_np[val_idx]\n", + "\n", + " # Model 1 Random Forest\n", + " rf = RandomForestRegressor(\n", + " n_estimators=300,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " # Model 2 CatBoost\n", + " cb = CatBoostRegressor(\n", + " iterations=2000,\n", + " learning_rate=0.03,\n", + " depth=6,\n", + " loss_function=\"MAE\",\n", + " random_seed=42,\n", + " verbose=0\n", + " )\n", + "\n", + " # Train odels\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " pred_rf = rf.predict(X_val)\n", + " pred_cb = cb.predict(X_val)\n", + "\n", + " # Average predictions\n", + " pred_avg = (pred_rf + pred_cb) / 2.0\n", + "\n", + " # MAE\n", + " fold_mae = mean_absolute_error(y_val, pred_avg)\n", + " fold_maes.append(fold_mae)\n", + "\n", + " print(f\"Fold {fold} MAE (Ensemble Avg): {fold_mae:.4f}\")\n", + "\n", + "print(\"-\" * 40)\n", + "print(f\"Mean MAE (Ensemble Avg): {np.mean(fold_maes):.4f}\")\n", + "print(f\"Std MAE (Ensemble Avg): {np.std(fold_maes):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/325/Q2.ipynb b/submissions_extracted/325/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d3892b352e501bceef48baa0e08bf4b50f46861d --- /dev/null +++ b/submissions_extracted/325/Q2.ipynb @@ -0,0 +1,331 @@ +{ + "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, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "from torch.optim import Adam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# 1) Convert to Tensors\n", + "# Images: float32, Labels: float32\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, drop_last=False)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, drop_last=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "xb, yb = next(iter(train_loader))\n", + "print(\"Batch X shape:\", xb.shape)\n", + "print(\"Batch y shape:\", yb.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "fig, axes = plt.subplots(2, 4, figsize=(12, 6))\n", + "axes = axes.flatten()\n", + "for i in range(8):\n", + " img = xb[i].permute(1, 2, 0).numpy() # H, W, C\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {yb[i].item():.0f}\")\n", + " axes[i].axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self, in_shape):\n", + " super().__init__()\n", + " c, h, w = in_shape\n", + " in_features = c * h * w\n", + "\n", + " self.net = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(in_features, 512), # 1st\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256), # 2nd\n", + " nn.ReLU(),\n", + " nn.Linear(256, 128), # 3rd\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1) # (output)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.net(x)" + ], + "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 x, y in loader:\n", + " x = x.to(device)\n", + " y = y.to(device)\n", + "\n", + " preds = model(x)\n", + " loss = loss_fn(preds, y)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item() * x.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_one_epoch(model, loader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for x, y in loader:\n", + " x = x.to(device)\n", + " y = y.to(device)\n", + "\n", + " preds = model(x)\n", + " loss = loss_fn(preds, y)\n", + "\n", + " total_loss += loss.item() * x.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Using device:\", device)\n", + "\n", + "xb, yb = next(iter(train_loader))\n", + "model = AgeRegressor(in_shape=xb.shape[1:]).to(device)\n", + "\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), lr=1e-3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(1, num_epochs + 1):\n", + " train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " val_loss = validate_one_epoch(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:02d}/{num_epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import torch\n", + "\n", + "# 1) Plot training & validation\n", + "plt.figure(figsize=(8, 5))\n", + "plt.plot(train_losses, label=\"Train Loss\")\n", + "plt.plot(val_losses, label=\"Val Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss\")\n", + "plt.title(\"Training vs 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", + "model.eval()\n", + "\n", + "xb, yb = next(iter(test_loader))\n", + "xb = xb.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(xb).cpu().squeeze(1)\n", + "actual = yb.squeeze(1)\n", + "\n", + "# first 8 images\n", + "fig, axes = plt.subplots(2, 4, figsize=(12, 6))\n", + "axes = axes.flatten()\n", + "\n", + "for i in range(8):\n", + " img = xb[i].cpu().permute(1, 2, 0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Pred: {preds[i].item():.1f} | True: {actual[i].item():.1f}\")\n", + " axes[i].axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/325/Q3.ipynb b/submissions_extracted/325/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cde516d4d2449eaddbf271268c5672dd9d1cb52c --- /dev/null +++ b/submissions_extracted/325/Q3.ipynb @@ -0,0 +1,311 @@ +{ + "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": [ + "!pip install catboost\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#read Data\n", + "Data = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n", + "Data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#Print head\n", + "Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Check data types and structure\n", + "Data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Descriptive statistic\n", + "Data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#check missing value\n", + "print(Data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Handle missing values\n", + "# we have many as i can drop it\n", + "Data = Data.dropna(subset=['P_2', 'B_2', 'D_142', 'D_143', 'D_144', 'D_145'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = Data.duplicated().sum()\n", + "duplicates" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = pd.get_dummies(Data, columns=cat_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", + "numerical_cols = Data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].value_counts(normalize=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fix scaled target\n", + "target_col = \"Target\"\n", + "df[target_col] = (df[target_col] > 0).astype(int)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "scores = []\n", + "\n", + "for tr_idx, va_idx in cv.split(X, y):\n", + " X_tr, X_va = X.iloc[tr_idx], X.iloc[va_idx]\n", + " y_tr, y_va = y.iloc[tr_idx], y.iloc[va_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=42\n", + " )\n", + "\n", + " model.fit(X_tr, y_tr)\n", + " y_pred = model.predict(X_va)\n", + " scores.append(f1_score(y_va, y_pred))\n", + "\n", + "print(\"Average F1 Score across folds:\", np.mean(scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# plot important feature\n", + "importances = model.get_feature_importance()\n", + "\n", + "top_k = 20\n", + "top_idx = np.argsort(importances)[-top_k:]\n", + "top_features = X.columns[top_idx]\n", + "top_vals = importances[top_idx]\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(top_features, top_vals)\n", + "plt.title(\"Top Feature Importances (CatBoost)\")\n", + "plt.xlabel(\"Importance\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#print name of most important\n", + "golden_feature = X.columns[int(np.argmax(importances))]\n", + "print(\"Golden feature:\", golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_golden = X[[golden_feature]]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for tr_idx, va_idx in cv.split(X_golden, y):\n", + " X_tr, X_va = X_golden.iloc[tr_idx], X_golden.iloc[va_idx]\n", + " y_tr, y_va = y.iloc[tr_idx], y.iloc[va_idx]\n", + "\n", + "full_scores = []\n", + "\n", + "for tr_idx, va_idx in cv.split(X, y):\n", + " X_tr, X_va = X.iloc[tr_idx], X.iloc[va_idx]\n", + " y_tr, y_va = y.iloc[tr_idx], y.iloc[va_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=42\n", + " )\n", + " model.fit(X_tr, y_tr)\n", + "\n", + " y_pred = model.predict(X_va)\n", + " full_scores.append(accuracy_score(y_va, y_pred))\n", + "\n", + "full_acc = np.mean(full_scores)\n", + "\n", + "print(\"Golden-only accuracy (avg across folds):\", np.mean(golden_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# comparison\n", + "print(\"Full model accuracy (avg across folds):\", full_acc)\n", + "print(\"Accuracy difference (Full - Golden):\", full_acc - np.mean(golden_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/326/Q1.ipynb b/submissions_extracted/326/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f43f47c6dfcccea3401220a8ba6d038372f9564d --- /dev/null +++ b/submissions_extracted/326/Q1.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import Required 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "download_path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", download_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "import os\n", + "\n", + "csv_file_path = os.path.join(download_path, 'Q1_data.csv')\n", + "df = pd.read_csv(csv_file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"DataFrame Info:\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "print(\"\\nSummary Table Generated by .describe() Method:\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# Target distribution\n", + "print(f\"DeliveryTime: {df['Delivery_Time'].sum()}\")\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df.drop('Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop rows with missing stat values\n", + "df = df.dropna(subset= stat_cols).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "print(df.duplicated())\n", + "df.drop_duplicates(inplace = True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "print(\"NO need\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature Scaling\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:\n", + "from sklearn.model_selection import train_test_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 # Add stratify for classification\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Initializing models and K-Fold cross-validation...\")\n", + "\n", + "# Determine the number of classes for one-hot encoding\n", + "num_classes = len(np.unique(y_encoded))\n", + "\n", + "# 1. Initialize the machine learning models\n", + "models = {\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n", + "}\n", + "\n", + "# 2. Create a KFold object\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "\n", + " model_name, model in models.items():\n", + " fold_loss = []\n", + "\n", + " fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Convert y_val_fold (true labels) into a one-hot encoded format\n", + " y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n", + "\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + " loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n", + " fold_losses.append(loss)\n", + "\n", + "print(model_losses)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "rf_grid = {\n", + " 'n_estimators': [50, 100, 200],\n", + " 'max_depth': [None, 10, 20, 30],\n", + " 'min_samples_split': [2, 5, 10],\n", + " 'min_samples_leaf': [1, 2, 4]\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_mse = mean_squared_error(y_train, y_train_pred)\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/326/Q2.ipynb b/submissions_extracted/326/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c060c5e8f462b13762c9f6c597e20b3fe4e9619c --- /dev/null +++ b/submissions_extracted/326/Q2.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\",path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import numpy as np\n", + "\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_size, hidden_sizes, output_size, dropout_rate=0.3):\n", + " super(SimpleNN, self).__init__()\n", + "\n", + " layers = []\n", + " prev_size = input_size\n", + "\n", + " # Create hidden layers\n", + " for i, hidden_size in enumerate(hidden_sizes):\n", + " layers.append(nn.Linear(prev_size, hidden_size))\n", + " layers.append(nn.ReLU())\n", + " layers.append(nn.Dropout(dropout_rate))\n", + " prev_size = hidden_size\n", + "\n", + " # Output layer\n", + " layers.append(nn.Linear(prev_size, output_size))\n", + "\n", + " self.model = nn.Sequential(*layers)\n", + "\n", + " def forward(self, x):\n", + " return self.model(x)\n", + "\n", + "def train_neural_network(X_train, y_train, X_val, y_val,\n", + " epochs=50, batch_size=32, learning_rate=0.001):\n", + "\n", + " # Convert to PyTorch tensors\n", + " X_train_tensor = torch.FloatTensor(X_train.values if hasattr(X_train, 'values') else X_train)\n", + " y_train_tensor = torch.LongTensor(y_train.values if hasattr(y_train, 'values') else y_train)\n", + " X_val_tensor = torch.FloatTensor(X_val.values if hasattr(X_val, 'values') else X_val)\n", + " y_val_tensor = torch.LongTensor(y_val.values if hasattr(y_val, 'values') else y_val)\n", + "\n", + " # Create datasets and dataloaders\n", + " train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + " train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "\n", + " # Initialize model, loss, optimizer\n", + " input_size = X_train.shape[1]\n", + " output_size = len(torch.unique(y_train_tensor))\n", + " model = SimpleNN(input_size, [64, 32], output_size)\n", + "\n", + " criterion = nn.CrossEntropyLoss() # For classification\n", + " # Use nn.MSELoss() for regression\n", + " optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", + "\n", + " # Training loop\n", + " train_losses = []\n", + " val_accuracies = []\n", + "\n", + " for epoch in range(epochs):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " # Batch training\n", + " for batch_X, batch_y in train_loader:\n", + " optimizer.zero_grad()\n", + " outputs = model(batch_X)\n", + " loss = criterion(outputs, batch_y)\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " # Validation\n", + " model.eval()\n", + " with torch.no_grad():\n", + " val_outputs = model(X_val_tensor)\n", + " _, val_preds = torch.max(val_outputs, 1)\n", + " val_acc = (val_preds == y_val_tensor).float().mean()\n", + "\n", + " train_losses.append(running_loss / len(train_loader))\n", + " val_accuracies.append(val_acc.item())\n", + "\n", + " if (epoch + 1) % 10 == 0:\n", + " print(f\"Epoch {epoch+1}/{epochs}, Loss: {running_loss/len(train_loader):.4f}, \"\n", + " f\"Val Acc: {val_acc:.4f}\")\n", + "\n", + " return model, train_losses, val_accuracies" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from tensorflow.keras.models import Sequential\n", + "from tensorflow.keras.layers import Dense, Dropout\n", + "from tensorflow.keras.optimizers import Adam\n", + "\n", + "model = Sequential([\n", + " Dense(64, activation='relu', input_shape=(input_size,)),\n", + " Dropout(0.3),\n", + " Dense(32, activation='relu'),\n", + " Dropout(0.3),\n", + " Dense(output_size, activation='softmax') # 'sigmoid' for binary\n", + "])\n", + "\n", + "model.compile(optimizer=Adam(learning_rate=0.001),\n", + " loss='categorical_crossentropy', # 'binary_crossentropy' for binary\n", + " metrics=['accuracy'])\n", + "\n", + "history = model.fit(X_train, y_train,\n", + " validation_data=(X_val, y_val),\n", + " epochs=50, batch_size=32, verbose=1)" + ], + "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", + "import matplotlib.pyplot as plt\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/326/Q3.ipynb b/submissions_extracted/326/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ce1393d275eda374c1d8ff9bf5e5489eca14b92 --- /dev/null +++ b/submissions_extracted/326/Q3.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import Required 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" + ], + "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:\n", + "import os\n", + "\n", + "csv_file_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(csv_file_path)" + ], + "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 1:\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": [ + "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:\n", + "print(df.duplicated())\n", + "df.drop_duplicates(inplace = True)" + ], + "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/327/Q1.ipynb b/submissions_extracted/327/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..afd699b57bfa6b7d37927276d69b1f8cd705f8f5 --- /dev/null +++ b/submissions_extracted/327/Q1.ipynb @@ -0,0 +1,347 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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 Required 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", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Load data\n", + "m_path = os.path.join(path, 'Q1_data.csv')\n", + "df_ma = pd.read_csv(m_path)\n", + "\n", + "print(f\"Dataset shape: {df_ma.shape}\")\n", + "df_ma.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check info\n", + "df_ma.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_ma.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_ma['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery_time\"')\n", + "plt.xlabel('A')\n", + "plt.ylabel('M')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_ma.drop(columns=['Order_ID'])" + ], + "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_ma.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_ma):\n", + " duplicates = df_ma.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_ma.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_ma)" + ], + "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", + "categories = pd.DataFrame({\"Animal\": ['cat', 'dog', 'cat', 'bird', 'dog']}) # DataFrame of one column\n", + "\n", + "print(\"Before encoding:\")\n", + "categories\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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Random data generation for scaling\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "\n", + "# Feature Scaling\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np # for random data generation\n", + "from sklearn.svm import SVC\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\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", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "# Predict and evaluate\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" + ], + "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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: 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_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/327/Q2.ipynb b/submissions_extracted/327/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3cc422267560441a289d94f3fb74caaa55364f83 --- /dev/null +++ b/submissions_extracted/327/Q2.ipynb @@ -0,0 +1,413 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "# Float for inputs, Long for classification targets, Float for regression targets\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\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 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", + "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 = 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", + "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 (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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", + "# 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/327/Q3.ipynb b/submissions_extracted/327/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3cfb0dbb45b923f6db48834f5596c70d5e5e24f9 --- /dev/null +++ b/submissions_extracted/327/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", + "# Import Required 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", + "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": [ + "# Task 2: Write your code here:\n", + "# Download latest version\n", + "m_path = os.path.join(path, 'Q3_data.csv')\n", + "df_ma = pd.read_csv(m_path)\n", + "\n", + "print(f\"Dataset shape: {df_ma.shape}\")\n", + "df_ma.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check info\n", + "df_ma.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_ma.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df_ma.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df_ma.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "import pandas as pd\n", + "\n", + "categories = pd.DataFrame({\"Animal\": ['cat', 'dog', 'cat', 'bird', 'dog']}) # DataFrame of one column\n", + "\n", + "print(\"Before encoding:\")\n", + "categories\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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:rom sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "# Random data generation for scaling\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "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", + "\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df_ma, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_ma[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_ma[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_ma, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np # for random data generation\n", + "from sklearn.svm import SVC\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "models = {\n", + "\n", + "\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\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", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "print(\"\\nClassification Metrics\\n\" + \"-\"*30)\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train a classification model\n", + "clf_model = LogisticRegression()\n", + "clf_model.fit(X_train, y_train)\n", + "y_pred = clf_model.predict(X_test)\n", + "\n", + "# Calculate metrics\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "precision = precision_score(y_test, y_pred)\n", + "recall = recall_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred)\n", + "\n", + "print(\"Accuracy :\", accuracy)\n", + "print(\"Precision:\", precision)\n", + "print(\"Recall :\", recall)\n", + "print(\"F1 Score :\", f1)\n", + "\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/328/Q1.ipynb b/submissions_extracted/328/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..db63cd2526c15de07c9261958b02b513ea72ebe6 --- /dev/null +++ b/submissions_extracted/328/Q1.ipynb @@ -0,0 +1,609 @@ +{ + "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", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.Delivery_Time" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(subset=['Delivery_Time'])" + ], + "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 4: Write your code here:\n", + "# delivery_time (target variable)\n", + "\n", + "\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\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 10\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "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 5: Write your code here:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "check_duplicates(df)\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, delivery_time):\n", + " print(\"Target Distribution:\")\n", + " print(df[delivery_time].value_counts(normalize=True))\n", + " df.countplot(x=df[delivery_time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)" + ], + "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_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Linear Regression Results\")\n", + "print(f\" Average MSE: {np.mean(lr_mse):.4f}\")\n", + "print(f\" Average RMSE: {np.mean(lr_rmse):.4f}\")\n", + "print(f\" Average R2: {np.mean(lr_r2):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + "\n", + " \"RandomForest\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = df['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = df['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=(10, 6))\n", + "plt.hist(df, 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": [ + "valid_pred = model.predict(X_valid)\n", + "model_mae = mean_absolute_error(y_valid, valid_pred)\n", + "print(f\"Model MAE: {model_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "models = {\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\")" + ], + "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", + "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()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/328/Q2.ipynb b/submissions_extracted/328/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ae45616de0a100e3b61768fa74c3a4042571d96 --- /dev/null +++ b/submissions_extracted/328/Q2.ipynb @@ -0,0 +1,485 @@ +{ + "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", + "df = pd.read_csv(\"/kaggle/input/q2-exam-data/labels.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "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", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# 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": [ + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n" + ], + "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": [ + "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": [ + "# 5. Display sample images\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", + "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": [ + "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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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 2 (Bonus): 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/328/Q3.ipynb b/submissions_extracted/328/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d38407b7330d947fbed3a657d49a6f92b806683e --- /dev/null +++ b/submissions_extracted/328/Q3.ipynb @@ -0,0 +1,392 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\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": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['D_41'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['D_42'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "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", + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: 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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, B_1):\n", + " print(\"Target Distribution:\")\n", + " print(df[B_1].value_counts(normalize=True))\n", + " sns.countplot(x=df[B_1])\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" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "# Calculate the majority class baseline\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "\n", + "print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n", + "print(f\"Baseline Precision: {baseline_precision:.4f}\")\n", + "print(f\"Baseline Recall: {baseline_recall:.4f}\")\n", + "print(f\"Baseline F1-Score: {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/329/Q1.ipynb b/submissions_extracted/329/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..01ed3584f8a8f72f88c221da4249b3fc259840fc --- /dev/null +++ b/submissions_extracted/329/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": [ + "# Task 1:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path,\"Q1_data.csv\")\n", + "\n", + "df= pd.read_csv(csv_path)\n", + "\n", + "#our target is delivery Time" + ], + "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", + "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:\n", + "df_clean = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def check_missing_values(df):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\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", + "print(one_hot_encode)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "# Task 5:\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"float64\"]).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:\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": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "# Task 1:\n", + "ature_cols= ['Distance_km', 'Preparation_Time_min',\n", + " 'Courier_Experience_yrs']\n", + "X = df_clean[ature_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", + "\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", + "# Task\n", + "X_train_scaled = scaler.fit_transform(X_train) #الفيت للحساب وترانسفورم لتطبيق\n", + "X_test_scaled = scaler.transform(X_test) #X_train_scaled ما استعملنا فيت هنا علشانها تست فنبغاه بس يطبق النتيجة اللي حسبها قبل في\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", + "model= RandomForestRegressor(n_estimators=100, max_depth = 20 , random_state=42 , n_jobs=5)\n", + "model.fit(X_train_scaled, y_test)\n", + "print('model traiannd')\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': ature_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/329/Q2.ipynb b/submissions_extracted/329/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cd60bf0f41585a2cc72e896f6441f2f03cdd3d3b --- /dev/null +++ b/submissions_extracted/329/Q2.ipynb @@ -0,0 +1,412 @@ +{ + "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", + "import torch\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim , output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #Third hidden layer\n", + "\n", + " z3= self.layer3(a2)\n", + " a3= self.layer3(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\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:\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\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:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "from torch.optim import Adam\n", + "num_epochs = 20\n", + "learning_rate = 0.002\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\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):\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/329/Q3.ipynb b/submissions_extracted/329/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/329/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/33/Q1.ipynb b/submissions_extracted/33/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4bef0973ded7eab943346e9e990996eeb04bd39a --- /dev/null +++ b/submissions_extracted/33/Q1.ipynb @@ -0,0 +1,244 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "\n", + "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": [ + "target = \"Delivery_Time\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df.drop(columns=[\"Order_ID\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (x.isnull().sum() / len(x)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "\n", + "df[target].fillna(df[target].median())\n", + "df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "categorical_columns =[\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "encoder = OneHotEncoder(handle_unknown = 'error', sparse_output = False, categories='auto')\n", + "encoder.fit(df[categorical_columns])\n", + "df_encoded = encoder.transform(df[categorical_columns])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#test\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target = \"Delivery_Time\"\n", + "x = df.drop(columns=[target,\"Weather\",\"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"])\n", + "y = df[target]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "model = RandomForestClassifier(n_estimators = 300, max_depth = 6, random_state = 42)\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, y):\n", + " X_fold_train, X_fold_val = x[train_idx], x[val_idx]\n", + " y_fold_train, y_fold_val = y[train_idx], y[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\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/33/Q2.ipynb b/submissions_extracted/33/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6240b697602ff7ffe6f508a38ffda8d54cfc5b39 --- /dev/null +++ b/submissions_extracted/33/Q2.ipynb @@ -0,0 +1,196 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "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", + "\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "\n", + "#i give up, there is no point of doing more.\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/33/Q3.ipynb b/submissions_extracted/33/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d7332237fc69dcbd82f220287bc51d8647726dca --- /dev/null +++ b/submissions_extracted/33/Q3.ipynb @@ -0,0 +1,162 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "#No point of doing this anymore" + ], + "execution_count": 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/330/Q1.ipynb b/submissions_extracted/330/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7a57d02f7dcc745e36216b1529c497e01ce6dec0 --- /dev/null +++ b/submissions_extracted/330/Q1.ipynb @@ -0,0 +1,334 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\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_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_copy = df.copy()\n", + "df_copy = df.drop(['Order_ID'], axis=1)\n", + "df_copy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_copy)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_copy = df_copy.dropna(subset=['Delivery_Time'])\n", + "check_missing_values(df_copy)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_copy)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df_copy)" + ], + "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_copy.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_copy[col] = le.fit_transform(df_copy[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_copy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "onehot_encoders = {}\n", + "for col in categorical_cols:\n", + " ol = OneHotEncoder() # Instantiate OneHotEncoder\n", + " df_copy[col] = ol.fit_transform(df_copy[col])\n", + " onehot_encoders[col] = ol\n", + "\n", + "df_copy" + ], + "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_copy.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_copy[numerical_cols] = scaler.fit_transform(df_copy[numerical_cols])\n", + "df_copy.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "# we do not need this bec our data is numorical" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_copy.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_copy['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.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "lr_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", + "model = RandomForestRegressor(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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predic\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(mae)\n", + "\n", + "# Calculate average loss across folds\n", + "print(f\"\\nMAE: {np.mean(lr_losses, axis=0):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = []\n", + "importances = model.feature_importances_\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "features = X.columns\n", + "plt.barh(features, importances)\n", + "plt.title('Random Forest Feature Importance')\n", + "plt.xlabel('Importance Score')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, edgecolor='black')\n", + "plt.title('Random Forest: predicted delivery time')\n", + "plt.xlabel('Predicted y_pred (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/330/Q2.ipynb b/submissions_extracted/330/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe04d62a3ab0a7dda04e0a7267f10fc59631a6ab --- /dev/null +++ b/submissions_extracted/330/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", + "\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.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\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", + "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", + "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", + "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", + "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", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim1, hidden_dim2, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim1)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim1, hidden_dim2)\n", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim2, hidden_dim2)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim2, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # 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)\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) # X_batch.size(0) --> give me just the num of photo\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "import torch.nn.functional as F\n", + "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\n", + "hidden_dim1 = 16\n", + "hidden_dim2 =12\n", + "output_dim = 10\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim1, hidden_dim2, output_dim).to(device)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from sklearn.metrics import mean_squared_error\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = mean_squared_error()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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 2 (Bonus): Write your code here:\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/330/Q3.ipynb b/submissions_extracted/330/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..62c62655c40a7774829ee8aa1961a35a5fb57d56 --- /dev/null +++ b/submissions_extracted/330/Q3.ipynb @@ -0,0 +1,220 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import 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)" + ], + "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": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns # 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", + "X = df_copy.drop(\"Target\", axis=1).astype(float)\n", + "y = df_copy['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", + "import numpy as np\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)" + ], + "execution_count": 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/331/Q1.ipynb b/submissions_extracted/331/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1a0fa99e4f85e81be7e3edc3b2c89ff6ab6180f5 --- /dev/null +++ b/submissions_extracted/331/Q1.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "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": [ + "# fix the path and read the csv file\n", + "# i use os.path.join to avoid any directory errors\n", + "file_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(file_path)\n", + "print(\"data loded corectly now!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# food distribution (target variable)\n", + "# ploting Delivery_Time to see if there is outliers\n", + "# i use hist plot with orange color\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "# Fixed: Changed 'delivery_time' to 'Delivery_Time' to match your data\n", + "plt.hist(df['Delivery_Time'], bins=30, color='orange', edgecolor='black')\n", + "\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.xlabel(\"Delivery Time (min)\")\n", + "plt.ylabel(\"count\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# removing Order_ID column from the data because its not useful\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Do we have missing values?\n", + "# checking for nulls in columns\n", + "# i will fill them with mean or just drop, lets drop to be safe\n", + "print(\"Missing values before:\", df.isnull().sum().sum())\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Do we have duplicate samples?\n", + "# finding if there is any duplicated rows\n", + "\n", + "print(\"Duplicated rows found:\", df.duplicated().sum())\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Do we have categorical columns?\n", + "\n", + "# this is better for the modle as a bonus\n", + "df = pd.get_dummies(df)\n", + "print(\"Encoding is finish\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "#.5\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "# scaling all features now\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "# puting it back to dataframe\n", + "X = pd.DataFrame(X_scaled, columns=X.columns)\n", + "print(\"y is now defined and data is scaled!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 6. Is the target imbalanced?\n", + "\n", + "print(\"target mean is:\", y.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# separating the data\n", + "# delivery_time is what we want to predict target\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "print(\"X shape is:\", X.shape)\n", + "print(\"Target y is ready!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i will use KFold because this is regression task\n", + "# stratified is only for classification labels\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "# starting the loop for training\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train_f, X_test_f = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train_f, y_test_f = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # define the modle Random Forest\n", + " # i will put 100 estimators\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + " # fiting the data now\n", + " rf_model.fit(X_train_f, y_train_f)\n", + "\n", + " # making prediction to check performance\n", + " predictions = rf_model.predict(X_test_f)\n", + "\n", + " # calculating MAE only as requested in task 4\n", + " fold_mae = mean_absolute_error(y_test_f, predictions)\n", + " mae_scores.append(fold_mae)\n", + " print(f\"one fold MAE score: {fold_mae:.4f}\")\n", + "\n", + "# print the final resault\n", + "print(\"\\n--- Final Results ---\")\n", + "print(\"Average MAE for all folds is:\", np.mean(mae_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "importances = rf_model.feature_importances_\n", + "features = X.columns\n", + "\n", + "# ploting it to see the result\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, importances, color='skyblue')\n", + "plt.title(\"Feature Importance - What makes delivery fast?\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Features\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# ploting the predictions to see the distribution\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(predictions, bins=20, color='lightgreen', edgecolor='black')\n", + "plt.title(\"Histogram of Predicted Delivery Times\")\n", + "plt.xlabel(\"Predicted Minutes\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostRegressor\n", + "\n", + "# kfold setup\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "ensemble_mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train_e, X_test_e = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train_e, y_test_e = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # traning 2 models\n", + " model_rf = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " model_cb = CatBoostRegressor(iterations=100, silent=True)\n", + "\n", + " model_rf.fit(X_train_e, y_train_e)\n", + " model_cb.fit(X_train_e, y_train_e)\n", + "\n", + " # average the predictions\n", + " p1 = model_rf.predict(X_test_e)\n", + " p2 = model_cb.predict(X_test_e)\n", + " final_p = (p1 + p2) / 2\n", + "\n", + " # calc mae\n", + " m = mean_absolute_error(y_test_e, final_p)\n", + " ensemble_mae_scores.append(m)\n", + "\n", + "# results\n", + "print(f\"Final Ensemble MAE: {np.mean(ensemble_mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/331/Q2.ipynb b/submissions_extracted/331/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..69c66c942e4053975238fb283b9a3cde9e164da7 --- /dev/null +++ b/submissions_extracted/331/Q2.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# checking if gpu is available\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"using device: {device}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\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", + "\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images, labels = next(iter(train_loader))\n", + "print(f\"Batch images shape: {images.shape}\")\n", + "print(f\"Batch labels shape: {labels.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(5):\n", + " plt.subplot(1, 5, i+1)\n", + "\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img.astype('uint8'))\n", + " plt.title(f\"Age: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class AgePredictionModel(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictionModel, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(3 * 64 * 64, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_model(model, train_loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " for images, labels in train_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item() * images.size(0)\n", + " return running_loss / len(train_loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_model(model, test_loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " with torch.no_grad():\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", + " running_loss += loss.item() * images.size(0)\n", + " return running_loss / len(test_loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = AgePredictionModel().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " train_loss = train_model(model, train_loader, criterion, optimizer, device)\n", + " val_loss = validate_model(model, test_loader, criterion, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f\"Epoch {epoch+1}/20: Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, label='Training Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss Over Epochs')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('MSE Loss')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval() # set model to evaluation mode\n", + "with torch.no_grad():\n", + " # getting a batch from test_loader\n", + " images, labels = next(iter(test_loader))\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " # making predictions\n", + " preds = model(images)\n", + "\n", + "# plotting results\n", + "plt.figure(figsize=(15, 6))\n", + "plt.plot(labels.cpu().numpy(), label='Actual Delivery Time', color='blue', marker='o')\n", + "plt.plot(preds.cpu().numpy(), label='Predicted Delivery Time', color='red', linestyle='--', marker='x')\n", + "plt.title(\"Actual vs Predicted Food Delivery Time\")\n", + "plt.xlabel(\"Sample Index\")\n", + "plt.ylabel(\"Time (minutes)\")\n", + "plt.legend()\n", + "plt.grid(True)\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/331/Q3.ipynb b/submissions_extracted/331/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5becf7939fe76bbf1322960d8cbce23a6067115b --- /dev/null +++ b/submissions_extracted/331/Q3.ipynb @@ -0,0 +1,310 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import warnings\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, accuracy_score\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "# reading the csv file from path\n", + "# i hope file name is corectly written\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", + "# showing the first rows to check data\n", + "# looks good i think\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# geting the information about columns and nulls\n", + "# i will use info function\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# show statical description for the data\n", + "# describe gives mean and std and other things\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# checking for any missing values first\n", + "# then i will drop them or fill, maybe drop is faster\n", + "print(df.isnull().sum())\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# looking for duplicate rows in the data\n", + "# i dont want same info twice\n", + "print(\"duplicated rows count:\", df.duplicated().sum())\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# change text columns to numbers so model can understand\n", + "# i will use get_dummies for simple encoding\n", + "df = pd.get_dummies(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# making all numerical values in same scale\n", + "# i useing StandardScaler as requested\n", + "scaler = StandardScaler()\n", + "\n", + "# i will separate target before scaling\n", + "# assume target column name is 'target' or 'default' (check your data info)\n", + "# for now i scale everything except target if i know name\n", + "# lets say we scale all numerical cols\n", + "num_cols = df.select_dtypes(include=['float64', 'int64']).columns\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# see if classes are equall or not\n", + "# very importent to check imbalance\n", + "target_counts = df['target'].value_counts() # change 'target' to actual label name\n", + "print(target_counts)\n", + "\n", + "if target_counts.iloc[0] / target_counts.iloc[1] > 2:\n", + " print(\"the data is imbalanced!\")\n", + "else:\n", + " print(\"the data looks okey\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# separating the target from features\n", + "# target is 'target' col, and X is evrything else\n", + "X = df.drop('target', axis=1) # make sure 'target' is the right name\n", + "y = df['target']\n", + "\n", + "print(\"X shape:\", X.shape)\n", + "print(\"y shape:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# i will use StratifiedKFold because its better for imbalance data\n", + "# and i will train CatBoost model inside the loop\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "scores = []\n", + "\n", + "# lets start the cross val now\n", + "for train_index, test_index in skf.split(X, y):\n", + " X_train_fold, X_test_fold = X.iloc[train_index], X.iloc[test_index]\n", + " y_train_fold, y_test_fold = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # define the catboost model with some params\n", + " # silent=True so it dont print too much logs\n", + " model = CatBoostClassifier(iterations=100, depth=6, learning_rate=0.1, silent=True)\n", + "\n", + " # fiting the model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # making prediction to evaluate\n", + " preds = model.predict(X_test_fold)\n", + "\n", + " # i use F1 Score becuase accuracy is not good for imbalanced\n", + " fold_f1 = f1_score(y_test_fold, preds)\n", + " scores.append(fold_f1)\n", + " print(f\"one fold F1 Score: {fold_f1:.4f}\")\n", + "\n", + "# finaly print the average score for all folds\n", + "print(\"\\n--- Final Results ---\")\n", + "print(\"Average F1 Score across all folds:\", np.mean(scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# checking wich feature is the most importent\n", + "# i will use the feature_importances_ from our catboost model\n", + "feat_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "# ploting it to see clearly\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(feature_names, feat_importances)\n", + "plt.title(\"Wich feature is the best?\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Features\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# finding the name of the feature with highest score\n", + "# i call it the golden feature as requested\n", + "golden_index = np.argmax(feat_importances)\n", + "golden_feature_name = feature_names[golden_index]\n", + "\n", + "print(\"--- The Resault ---\")\n", + "print(\"The Golden Feature is:\", golden_feature_name)\n", + "print(\"This is the most powerfull predictor in the data!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# now i will try to train the model with ONLY the best feature\n", + "# i want to see if one feature is enough to get good resault\n", + "# creating new X with just one col\n", + "X_golden = X[[golden_feature_name]]\n", + "\n", + "# i use same loop and same skf for fair comparison\n", + "golden_scores = []\n", + "\n", + "print(\"starting training with golden feature only...\")\n", + "\n", + "for train_idx, test_idx in skf.split(X_golden, y):\n", + " X_train_g, X_test_g = X_golden.iloc[train_idx], X_golden.iloc[test_idx]\n", + " y_train_g, y_test_g = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # same catboost model\n", + " model_g = CatBoostClassifier(iterations=100, silent=True)\n", + " model_g.fit(X_train_g, y_train_g)\n", + "\n", + " # predict and calculate accuracy this time for compare\n", + " g_preds = model_g.predict(X_test_g)\n", + " from sklearn.metrics import accuracy_score\n", + " acc = accuracy_score(y_test_g, g_preds)\n", + " golden_scores.append(acc)\n", + "\n", + "# printing and comparing\n", + "avg_golden_acc = np.mean(golden_scores)\n", + "print(f\"\\nAccuracy with ONLY Golden Feature: {avg_golden_acc:.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/332/Q1.ipynb b/submissions_extracted/332/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2b6441fcf9ab4202b5dbdacc61fdcd2e5a3e0486 --- /dev/null +++ b/submissions_extracted/332/Q1.ipynb @@ -0,0 +1,362 @@ +{ + "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", + "\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_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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 (target variable)\n", + "import matplotlib.pyplot as plt\n", + "\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('Food Delivery Time')\n", + "plt.ylabel('Time(Min)')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean=df.drop(columns=\"Order_ID\", axis=1)" + ], + "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.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " cols=[missing_values]\n", + "check_missing_values(df_clean)\n", + "\n", + "df_clean.dropna(subset=['Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")\n", + "#Target is imbalanced\n", + "#Target is imbalanced\n" + ], + "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['Delivery_Time'].astype(float)" + ], + "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 sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " }\n", + "\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + " n_splits = 5 # K\n", + "y.dropna()\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "y.fillna('none')\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Food Delivery Time')\n", + "plt.ylabel('Time(Min)')\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/332/Q2.ipynb b/submissions_extracted/332/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b815c8bdfae75b95b657343f3c4aa4ce3d44472d --- /dev/null +++ b/submissions_extracted/332/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", + "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", + "# 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.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "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(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "> Data now is ready for the model ! you'll now build the model class." + ], + "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", + "ef 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", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\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(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", + "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/332/Q3.ipynb b/submissions_extracted/332/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..981ea860d739454c7e68195e6056c8d58cc3b36f --- /dev/null +++ b/submissions_extracted/332/Q3.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost lightgbm tqdm -q\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "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", + "\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", + "Q_3 = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q_3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean=df\n", + "def check_missing_values(df_clean):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " cols=[missing_values]\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\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 StandardScaler\n", + "\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Target\")\n", + "#Target is imbalanced\n", + "#Target is imbalanced\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Target\", axis=1).astype(float)\n", + "y = df['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", + "n_splits = 5 # K=5 Folds\n", + "# sigmoid in NumPy\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + "y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\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", + "CatBoost.fit(X_train, y_train) # train\n", + "y_pred = CatBoost.predict(X_test)\n", + "all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "'''\n", + "most important feature is:\n", + "P_2\n", + "B_2\n", + "D_142\n", + "D_144\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/333/Q1.ipynb b/submissions_extracted/333/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a3d96f2e8ac0d7f6dbb8608a7c2df0834fe727a --- /dev/null +++ b/submissions_extracted/333/Q1.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery 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_calen = df_data.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_data[col] = df_data[col].fillna('unknown')\n", + "\n", + "df_data['Courier_Experience_yrs']=df_data['Courier_Experience_yrs'].fillna(df_data['Courier_Experience_yrs'].mean())\n", + "df_data['Delivery_Time']=df_data['Delivery_Time'].fillna(df_data['Delivery_Time'].mean())" + ], + "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 LabelEncoder\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_data[col] = le.fit_transform(df_data[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "df_data['timing_cost'] = 24 - df_data['Time_of_Day']\n", + "\n", + "\n", + "df_data['prep_take'] = df_data['Time_of_Day'] - (df_data['Preparation_Time_min'])\n", + "\n", + "df_data['experice_by_distance'] = df_data['Courier_Experience_yrs'] * df_data['Distance_km']\n", + "\n", + "df_data[['timing_cost', 'prep_take', 'experice_by_distance']]\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_data) # Apply fit_transform" + ], + "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 =['timing_cost', 'prep_take', 'experice_by_distance','Weather', 'Preparation_Time_min', 'Distance_km', 'Traffic_Level','Vehicle_Type','Time_of_Day','Courier_Experience_yrs']\n", + "\n", + " #columns=['Weather', 'Preparation_Time_min', 'Distance_km', 'Traffic_Level','Vehicle_Type','Time_of_Day','Courier_Experience_yrs']\n", + "\n", + "X = df_data[feature_cols]\n", + "y = df_data['Delivery_Time']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\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", + "\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)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: {mae:,.2f}\")\n", + "\n", + "mae_scores = []\n", + "\n", + "mae_scores.append(mean_absolute_error(y_train, y_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\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", + "# delivery time hist\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/333/Q2.ipynb b/submissions_extracted/333/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9c2693cb3867ee3b2918a6a247006f18bbbaab51 --- /dev/null +++ b/submissions_extracted/333/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", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\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", + "\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}\")\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=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot()\n", + " plt.imshow(images[i].squeeze())\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "import torch.nn as nn\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4= nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #third hidden layer\n", + " z3 = self.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", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "from torch.optim import Adam\n", + "\n", + "# Device 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", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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", + "# 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/333/Q3.ipynb b/submissions_extracted/333/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d770971cf2e6fce496dcf4b168fead07f5f993f --- /dev/null +++ b/submissions_extracted/333/Q3.ipynb @@ -0,0 +1,169 @@ +{ + "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 pandas as pd\n", + "import os\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", + "\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:" + ], + "execution_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/334/Q1.ipynb b/submissions_extracted/334/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6e81394af8444107c5bc4dc106e211f565bb70a5 --- /dev/null +++ b/submissions_extracted/334/Q1.ipynb @@ -0,0 +1,306 @@ +{ + "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", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import os\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.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 = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.dropna(subset='Delivery_Time').copy()\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "\n", + "\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " 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_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#############################################################################################################################\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "####################################################################################33\n", + "#BONUS\n", + "#from sklearn.preprocessing import OneHotEncoder\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "#data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols)\n", + "\n", + "#print('\\nData after encoding:\\n', data_onehot_encoded)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\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 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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "models = {\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100)\n", + "}\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 = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\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", + "\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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/334/Q2.ipynb b/submissions_extracted/334/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2f82a33a83349e252fc299137ecef4a36989e086 --- /dev/null +++ b/submissions_extracted/334/Q2.ipynb @@ -0,0 +1,376 @@ +{ + "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", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\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", + "\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", + " # Forward pass\n", + " outputs = model(X_batch)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # 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", + "# Model parameters\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 1\n", + "# Instantiate regression 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", + "criterion = nn.MSELoss()\n", + "\n", + "num_epochs = 20\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\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/334/Q3.ipynb b/submissions_extracted/334/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..077fbf0a0a01ab6359414c6e050432f94aed2f64 --- /dev/null +++ b/submissions_extracted/334/Q3.ipynb @@ -0,0 +1,239 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import os\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", + "\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", + "df.drop(columns=['D_142'])\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", + "\n", + "\n", + "\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#############################################################################################################################\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])\n", + "\n", + "scaler = StandardScaler()\n", + "\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:" + ], + "execution_count": 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\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/335/Q1.ipynb b/submissions_extracted/335/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c20d1abb02634dacacd8c4ca3e2d0f3fe953dd10 --- /dev/null +++ b/submissions_extracted/335/Q1.ipynb @@ -0,0 +1,354 @@ +{ + "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.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "\n", + "\n", + "import seaborn as sns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import warnings\n", + "\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier\n", + "from sklearn.svm import SVR, SVC\n", + "from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier\n", + "\n", + "\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(Food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"count: {df_food['Delivery_Time'].sum()}\")\n", + "print(f\"mean: {(df_food['Delivery_Time'] == 0).sum()}\")\n", + "\n", + "\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_food[stat_cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_food.dropna(subset=['Order_ID']).copy()\n", + "print(f\"After dropping Order_ID {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_food)" + ], + "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", + "\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + "\n", + " for i in range(m):\n", + "\n", + " class_label = int(y[i])\n", + "\n", + "\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + " df_clean[['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']].head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\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 if TASK==\"classification\" else None\n", + ")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "\n", + "\n", + "models = {\n", + " 'Logistic Regression': LogisticRegression(solver='liblinear', max_iter=200, random_state=42),\n", + " 'Decision Tree': DecisionTreeClassifier(random_state=42),\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n", + " 'SVM': SVC(probability=True, random_state=42) # probability=True is needed for .predict_proba\n", + "}\n", + "\n", + "\n", + "models.fit(X_train, y_train)\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model_losses = {}\n", + "\n", + "for tr, te in kf.split(X):\n", + "\n", + " X_tr, X_te = X.iloc[tr], X.iloc[te]\n", + " y_tr, y_te = y.iloc[tr], y.iloc[te]\n", + "\n", + " sc = StandardScaler()\n", + " X_tr = sc.fit_transform(X_tr)\n", + " X_te = sc.transform(X_te)\n", + "\n", + " m = RandomForestRegressor()\n", + " m.fit(X_tr, y_tr)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/335/Q2.ipynb b/submissions_extracted/335/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/335/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/335/Q3.ipynb b/submissions_extracted/335/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..638dd5a8a16a7197f01918db0fcfe4f88ad62b66 --- /dev/null +++ b/submissions_extracted/335/Q3.ipynb @@ -0,0 +1,263 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "\n", + "\n", + "import seaborn as sns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import warnings\n", + "\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier\n", + "from sklearn.svm import SVR, SVC\n", + "from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier\n", + "\n", + "\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "Food_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Food_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.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + "\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + "\n", + " for i in range(m):\n", + "\n", + " class_label = int(y[i])\n", + "\n", + "\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + " df_clean[['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']].head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + "\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + "\n", + " for i in range(m):\n", + "\n", + " class_label = int(y[i])\n", + "\n", + "\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + " df_clean[['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']].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/336/Q1.ipynb b/submissions_extracted/336/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..caa9f08f3fa1fe94d9a09c08d1244f8a9042cb75 --- /dev/null +++ b/submissions_extracted/336/Q1.ipynb @@ -0,0 +1,345 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "import pandas as pd\n", + "import matplotlib.pyplot as plt #\n", + "import seaborn as sns\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", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "print(\"\\nDataset Info:\")\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "print(\"\\nStatistical Description:\") #\n", + "display(df.describe())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5\n", + "plt.figure(figsize=(8,5))\n", + "sns.histplot(df[\"Delivery_Time\"], kde=True, bins=30, color=\"steelblue\")\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "import pandas as pd\n", + "from sklearn.preprocessing import OneHotEncoder, StandardScaler\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import Pipeline\n", + "\n", + "df = df.drop(columns=['Order_ID'], errors='ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "print(\"Missing values per column:\")\n", + "print(df.isnull().sum())\n", + "\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()\n", + "cat_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(\"\\nMissing values after imputation:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "df = df.drop_duplicates()\n", + "after = df.shape[0]\n", + "\n", + "print(f\"\\nDuplicates removed: {after}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "df_encoded = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Features and target\n", + "X = df_encoded.drop(columns=[\"Delivery_Time\"])\n", + "y = df_encoded[\"Delivery_Time\"]\n", + "\n", + "# Standard scaling\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "sns.histplot(X, kde=True, bins=30)\n", + "plt.title(\"Delivery Time Distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\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", + "# Assuming X_scaled and y are already prepared from previous steps\n", + "\n", + "# 1. Define KFold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task2\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "models = [] # keep models if you want to reuse the last one for plots\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X_scaled), 1):\n", + " X_train, X_val = X_scaled[train_idx], X_scaled[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " rf.fit(X_train, y_train)\n", + " y_pred = rf.predict(X_val)\n", + "\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + " models.append(rf)\n", + "\n", + " print(f\"Fold {fold} | MAE: {mae:.4f}\")\n", + "\n", + "print(f\"\\nAverage MAE across folds: {np.mean(mae_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "final_model = models[-1]\n", + "\n", + "importances = final_model.feature_importances_\n", + "feature_names = X.columns\n", + "\n", + "feat_imp = pd.Series(importances, index=feature_names).sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(10,6))\n", + "sns.barplot(x=feat_imp.values, y=feat_imp.index, color=\"steelblue\")\n", + "plt.title(\"Feature Importance (RandomForest)\")\n", + "plt.xlabel(\"Importance\")\n", + "plt.ylabel(\"Features\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "all_preds = []\n", + "all_true = []\n", + "\n", + "for train_idx, val_idx in kf.split(X_scaled):\n", + " X_train, X_val = X_scaled[train_idx], X_scaled[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " rf.fit(X_train, y_train)\n", + " y_pred = rf.predict(X_val)\n", + "\n", + " all_preds.extend(y_pred)\n", + " all_true.extend(y_val)\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "sns.histplot(all_preds, kde=True, bins=30, color=\"darkorange\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores_ensemble = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X_scaled), 1):\n", + " X_train, X_val = X_scaled[train_idx], X_scaled[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " cb = CatBoostRegressor(\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " n_estimators=300,\n", + " random_state=42,\n", + " verbose=False\n", + " )\n", + "\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + " rf_pred = rf.predict(X_val)\n", + " cb_pred = cb.predict(X_val)\n", + "\n", + " ensemble_pred = (rf_pred + cb_pred) / 2.0\n", + "\n", + " mae = mean_absolute_error(y_val, ensemble_pred)\n", + " mae_scores_ensemble.append(mae)\n", + "\n", + " print(f\"Fold {fold} | Ensemble MAE: {mae:.4f}\")\n", + "\n", + "print(f\"\\nAverage Ensemble MAE across folds: {np.mean(mae_scores_ensemble):.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/336/Q2.ipynb b/submissions_extracted/336/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf7a3eb2de98eea64af56ae94382128755eca687 --- /dev/null +++ b/submissions_extracted/336/Q2.ipynb @@ -0,0 +1,309 @@ +{ + "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.\n", + "import torch\n", + "\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "X_train_tensor = X_train_tensor.permute(0, 3, 1, 2)\n", + "X_test_tensor = X_test_tensor.permute(0, 3, 1, 2)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2.\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3.\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4.\n", + "for images, labels in train_loader:\n", + " print(\"Batch image shape:\", images.shape)\n", + " print(\"Batch label shape:\", labels.shape)\n", + " break\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5.\n", + "import matplotlib.pyplot as plt\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(8):\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " plt.subplot(2, 4, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {labels[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "import torch.nn as nn\n", + "\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(3*36*36, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x.squeeze()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "def train_one_epoch(model, loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + "\n", + " for X, y in loader:\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(X)\n", + " loss = loss_fn(preds, y)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "def validate(model, loader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0\n", + "\n", + " with torch.no_grad():\n", + " for X, y in loader:\n", + " X, y = X.to(device), y.to(device)\n", + " preds = model(X)\n", + " loss = loss_fn(preds, y)\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "model = AgeRegressor().to(device)\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5\n", + "epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(epochs):\n", + " train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " val_loss = validate(model, test_loader, loss_fn, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch {epoch+1}/{epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "plt.figure(figsize=(8,5))\n", + "plt.plot(train_losses, label=\"Train Loss\")\n", + "plt.plot(val_losses, label=\"Validation Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"MSE Loss\")\n", + "plt.title(\"Training vs Validation Loss\")\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "model.eval()\n", + "X_batch, y_batch = next(iter(test_loader))\n", + "X_batch = X_batch.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(X_batch).cpu()\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "for i in range(8):\n", + " img = X_batch[i].cpu().permute(1, 2, 0).numpy()\n", + " plt.subplot(2, 4, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred: {preds[i]:.1f}\\nActual: {y_batch[i]:.0f}\")\n", + " plt.axis(\"off\")\n", + "\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/336/Q3.ipynb b/submissions_extracted/336/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1cf5d19f471e2e5ef66750831f18d36e445187d --- /dev/null +++ b/submissions_extracted/336/Q3.ipynb @@ -0,0 +1,271 @@ +{ + "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\n", + "\n", + "import pandas as pd\n", + "import os\n", + "\n", + "file_path = os.path.join(path, \"Q3_data.csv\") # 'path' from kagglehub cell\n", + "df = pd.read_csv(file_path)\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 1\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(exclude=[\"int64\", \"float64\"]).columns\n", + "\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "print(\"Duplicates before:\", df.duplicated().sum())\n", + "df = df.drop_duplicates()\n", + "print(\"Duplicates after:\", df.duplicated().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "for col in cat_cols:\n", + " df[col] = le.fit_transform(df[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5\n", + "target_col = \"target\" # change if your target column has a different name\n", + "print(df[target_col].value_counts(normalize=True))\n", + "print(df[target_col].value_counts())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "from catboost import CatBoostClassifier\n", + "import numpy as np\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "acc_scores = []\n", + "\n", + "for train_idx, val_idx in skf.split(X, y):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " verbose=0,\n", + " random_seed=42\n", + " )\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + "\n", + " f1 = f1_score(y_val, y_pred)\n", + " acc = accuracy_score(y_val, y_pred)\n", + "\n", + " f1_scores.append(f1)\n", + " acc_scores.append(acc)\n", + "\n", + "print(\"Average F1 Score across folds:\", np.mean(f1_scores))\n", + "print(\"Average Accuracy across folds:\", np.mean(acc_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Train once on full data to get feature importances\n", + "final_model = CatBoostClassifier(verbose=0, random_seed=42)\n", + "final_model.fit(X, y)\n", + "\n", + "importances = final_model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "sorted_importances = importances[sorted_idx]\n", + "sorted_features = feature_names[sorted_idx]\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.bar(range(len(sorted_importances)), sorted_importances)\n", + "plt.xticks(range(len(sorted_importances)), sorted_features, rotation=90)\n", + "plt.title(\"Feature Importance\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "golden_feature = sorted_features[0]\n", + "print(\"Golden feature:\", golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores_golden = []\n", + "acc_scores_golden = []\n", + "\n", + "for train_idx, val_idx in 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 = CatBoostClassifier(\n", + " verbose=0,\n", + " random_seed=42\n", + " )\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + "\n", + " f1_scores_golden.append(f1_score(y_val, y_pred))\n", + " acc_scores_golden.append(accuracy_score(y_val, y_pred))\n", + "\n", + "print(\"Golden feature only - Average F1:\", np.mean(f1_scores_golden))\n", + "print(\"Golden feature only - Average Accuracy:\", np.mean(acc_scores_golden))" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/337/Q1.ipynb b/submissions_extracted/337/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..17739fa2e5c873b5866e173b9903680caf3a449f --- /dev/null +++ b/submissions_extracted/337/Q1.ipynb @@ -0,0 +1,297 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\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", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "clear_output()\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\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'])" + ], + "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", + "\n", + "stat_cols = ['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "\n", + "\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", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "categories = pd.DataFrame({\"Animal\": categorical_cols }) # DataFrame of one column\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Target distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('target Distribution')\n", + "plt.show()\n", + "# the plot show it is balance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\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}\")\n", + "\n", + "\n", + "\n", + "models = {\n", + "\"Random Forest Classifier\": RandomForestClassifier(n_estimators=100)\n", + "}\n", + "models[\"Ensemble\"] = VotingClassifier(estimators=[\n", + " ('gnb', models[\"Random Forest Classifier\"])])\n", + "\n", + "for model_name, model in models.items():\n", + " scores_accuracy = []\n", + " scores_precision = []\n", + " scores_recall = []\n", + " scores_f1 = []\n", + " # Stratified 5-Fold Cross-Validation\n", + " skf = KFold(n_splits=5)\n", + " for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\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:" + ], + "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/337/Q2.ipynb b/submissions_extracted/337/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/337/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/337/Q3.ipynb b/submissions_extracted/337/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8919d579a321bce084caedb5ba6ed32e6f04df2b --- /dev/null +++ b/submissions_extracted/337/Q3.ipynb @@ -0,0 +1,248 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\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", + "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)\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()\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "\n", + "\n", + "df.isnull().fillna(df.isnull().mean())\n", + "\n", + "print(f\"Shape after cleaning: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 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 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "# no Categorical virable" + ], + "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) # Apply fit_transform" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('target Distribution')\n", + "plt.show()\n", + "# the plot show it is imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "models = {\n", + "\"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n", + "}\n", + "models[\"Ensemble\"] = VotingClassifier(estimators=[\n", + "('lr', models[\"CatBoost Classifier\"])])\n", + "\n", + "for model_name, model in models.items():\n", + " scores_accuracy = []\n", + " scores_precision = []\n", + " scores_recall = []\n", + " scores_f1 = []\n", + " # Stratified 5-Fold Cross-Validation\n", + " skf = KFold(n_splits=5)\n", + " for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\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:" + ], + "execution_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/338/Q1.ipynb b/submissions_extracted/338/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d699ff0c0fb4554eef4fe7fe8fce1ed3185985bd --- /dev/null +++ b/submissions_extracted/338/Q1.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "df_clean = df_clean.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df_clean.isnull().sum())\n", + "df_clean.describe()\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "cols = [\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\"]\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "for col in cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "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", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\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", + "print(f\"Mean Absolute Error: {mean_absolute_error(y_test, y_pred):.4f}\\n\")\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "\n", + "cols_f = [\"Courier_Experience_yrs\",\"Preparation_Time_min\",\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\", \"Distance_km\"]\n", + "importance = pd.DataFrame({\n", + " 'feature': cols_f,\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_clean['Delivery_Time'], bins=50, edgecolor='black', color='green')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('delivery time')\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/338/Q2.ipynb b/submissions_extracted/338/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f17ae2f9b5c66a180141b77374b0661eda234b27 --- /dev/null +++ b/submissions_extracted/338/Q2.ipynb @@ -0,0 +1,373 @@ +{ + "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 kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\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):\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\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\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", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device).view(-1, 1).to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "learning_rate = 0.001\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), lr = learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Device configuration\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\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('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/338/Q3.ipynb b/submissions_extracted/338/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..be955140fa3141d1611bfbc8fadb0c2f04b134db --- /dev/null +++ b/submissions_extracted/338/Q3.ipynb @@ -0,0 +1,248 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "import os\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n", + "print(df.isnull().sum())\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "def check_missing_values(df_clean):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)\n", + "missing_values = df.isnull().sum()\n", + "cols = missing_values[missing_values > 10000]\n", + "print(cols)\n", + "#df_clean= df_clean.drop(cols, axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "for col in df_clean.select_dtypes(include=[\"object\"]).columns:\n", + " df_clean[col] = label_encoder.fit_transform(df_clean[col])" + ], + "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(\"\")\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": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"\", axis=1).astype(float)\n", + "y = df_clean[''].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 RandomForestClassifier\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(f\"Mean Absolute Error: {mean_absolute_error(y_test, y_pred):.4f}\\n\")\n", + "df_clean.info()" + ], + "execution_count": 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/339/Q1.ipynb b/submissions_extracted/339/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..109deab7e184b8cd2fdbee45b7ec5596121ce143 --- /dev/null +++ b/submissions_extracted/339/Q1.ipynb @@ -0,0 +1,298 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler\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_time_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery_time = pd.read_csv(delivery_time_path)\n", + "\n", + "\n", + "print(f\"Dataset shape: {df_delivery_time.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery_time.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check data types and structure\n", + "df_delivery_time.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Descriptive statistics\n", + "df_delivery_time.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery_time" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# delivery time distribution (target variable)\n", + "plt.figure(figsize=(10,5 ))\n", + "plt.hist(df_delivery_time['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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": [ + "# 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": [ + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Standardize features using StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# split features from targets\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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/339/Q2.ipynb b/submissions_extracted/339/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3d497aca2bdbdb5cd7e57aba2dcbe7e1795f19a4 --- /dev/null +++ b/submissions_extracted/339/Q2.ipynb @@ -0,0 +1,321 @@ +{ + "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": [ + "# 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": [ + "# 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": [ + "# 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": [ + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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\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) # 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": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/339/Q3.ipynb b/submissions_extracted/339/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/339/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/34/Q1.ipynb b/submissions_extracted/34/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..db7bec87b3c05064bdcdd51e3a28f726d1b251ae --- /dev/null +++ b/submissions_extracted/34/Q1.ipynb @@ -0,0 +1,216 @@ +{ + "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", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "def check_target_distribution(df, 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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: we no work" + ], + "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:nd CatBoostRegressor.\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/340/Q1.ipynb b/submissions_extracted/340/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..78820a8b8af4a4f45135fdac47e94e2f2cbcc86b --- /dev/null +++ b/submissions_extracted/340/Q1.ipynb @@ -0,0 +1,239 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "from sklearn.preprocessing import LabelEncoder,StandardScaler\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", + "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": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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": [ + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Delivery Time: {df_Q1['Delivery_Time'].sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df_Q1.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = ['Weather','Traffic_Level','Time_of_Day',]\n", + "df_clean = df_Q1[categorical_cols].copy()\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": [ + "numerical_cols = df_Q1.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop('Delivery_Time')\n", + "scaler = StandardScaler()\n", + "df_Q1[numerical_cols] = scaler.fit_transform(df_Q1[numerical_cols])\n", + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df_Q3, target_column):\n", + " print(\"Target Distribution:\")\n", + " df[target_column].hist()\n", + " plt.show()\n", + " check_target_imbalance(df_Q3, \"Air Quality\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_Q1.drop(\"Delivery_Time\",axis=1)\n", + "y = df_Q1['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "X_train_scaled = scaler.fit_transform(X_train)\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": [ + "import matplotlib.pyplot as plt\n", + "transmission_counts = df_Q1['delivery_time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(transmission_counts.index, transmission_counts.values, color='teal')\n", + "plt.title('delivery time')\n", + "plt.xlabel('delivery Type')\n", + "plt.ylabel('Count')\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/340/Q2.ipynb b/submissions_extracted/340/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d89d8f7c385f6eeb617efefc279573d595eabf9a --- /dev/null +++ b/submissions_extracted/340/Q2.ipynb @@ -0,0 +1,199 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "a = torch.tensor([1600, 3, 36, 36])\n", + "c = torch.tensor([400, 3, 36, 36])\n", + "d = torch.tensor([1600,])\n", + "e = torch.tensor([400,])\n", + "\n", + "b = torch.randn([3])\n", + "print(\"a:\", a)\n", + "print(\"c:\", c)" + ], + "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/340/Q3.ipynb b/submissions_extracted/340/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..88ea5e6071c3b414170e0e98b14aa61b51eb8b32 --- /dev/null +++ b/submissions_extracted/340/Q3.ipynb @@ -0,0 +1,196 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "from sklearn.preprocessing import LabelEncoder,StandardScaler\n", + "import matplotlib.pyplot as plt\n", + "\n", + "import pandas as pd\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "df_Q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df_Q3.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df_Q3.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df_Q3.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"P_2\")\n", + "scaler = StandardScaler()\n", + "df_Q3[numerical_cols] = scaler.fit_transform(df_Q3[numerical_cols])\n", + "df_Q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + "\n", + "\n", + "check_target_imbalance(df_Q3, \"P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_Q3.drop(\"P_2\",axis=1)\n", + "y = df_Q3['P_2']" + ], + "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", + "feature_cols = ['D_39',\t'B_1',\t'B_2',\t'R_1',]\n", + "df_clean = df_Q3[feature_cols].copy()\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['P_2']\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 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/341/Q1.ipynb b/submissions_extracted/341/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9f2137c0d429e775ccf67652bc34287241eda1a6 --- /dev/null +++ b/submissions_extracted/341/Q1.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import tqdm\n", + "from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# 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", + "foods_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(foods_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=50, edgecolor='black')\n", + "plt.title('Time Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop(['Order_ID'],axis=1)\n", + "print(df.shape, df_clean.shape) # to make sure" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "ddf_clean = df_clean.copy # a copy of the data just in case\n", + "missing = df_clean.isnull().sum()\n", + "df_clean = df_clean.dropna()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "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": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T 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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\",axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)\n", + "#X = df_clean.drop(['Delivery_Time'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "# Task 3\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", + "# Task 4\n", + "y_pred = model.predict(X_test)\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", + "# Task 5\n", + "kfold = KFold(n_splits=5, shuffle=True)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "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/341/Q2.ipynb b/submissions_extracted/341/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7d3751facbd19dc8b3f975f883291a08651271ed --- /dev/null +++ b/submissions_extracted/341/Q2.ipynb @@ -0,0 +1,355 @@ +{ + "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\n", + "import kagglehub\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.float64)\n", + "X_test = torch.tensor(X_test, dtype=torch.float64)\n", + "y_train = torch.tensor(y_train, dtype=torch.float64)\n", + "y_test = torch.tensor(y_test, dtype=torch.float64)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(5):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4layer, self).__init__()\n", + "\n", + " # First layer:\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim,hidden_dim)\n", + " # Output layer:\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", + " # Third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\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\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# model\n", + "input_dim = 3 * 36 * 36 # Image dims\n", + "hidden_dim = 18 # personal choice\n", + "output_dim = 10 # from 1 to 10\n", + "model = NN4layer(input_dim, hidden_dim, output_dim).to(device)\n", + "# loss\n", + "criterion = nn.CrossEntropyLoss()\n", + "# optimizer\n", + "learning_rate = 0.001\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "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!')\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/341/Q3.ipynb b/submissions_extracted/341/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fd05a7231284f795d02bfd99a49023fe50cc5412 --- /dev/null +++ b/submissions_extracted/341/Q3.ipynb @@ -0,0 +1,198 @@ +{ + "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", + "# Download latest version\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", + "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", + "df_clean = df.fillna(1)\n", + "df_clean" + ], + "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_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "model = StandardScaler()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"\")" + ], + "execution_count": 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/342/Q1.ipynb b/submissions_extracted/342/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..685d655bc794228d80a651d9eb25aade0362224b --- /dev/null +++ b/submissions_extracted/342/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "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": [ + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\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 tqdm import tqdm\n", + "%matplotlib inline\n", + "import warnings" + ], + "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_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1_data = pd.read_csv(Q1_data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_Q1_data.shape}\")\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "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": [ + "\n", + "\n", + "# Check Missing values\n", + "print(\"Missing values:\")\n", + "print(df_Q1_data.isnull().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"Delivery Time : {df_Q1_data['Delivery_Time'].sum()}\")\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID' , 'Distance_km','Preparation_Time_min', 'Weather' ,'Traffic_Level', 'Time_of_Day', 'Vehicle_Type' , 'Preparation_Time_min' , 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_Q1_data.dropna(subset=cols).copy()\n", + "df_clean = df_Q1_data.drop(columns=['Order_ID'])\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['Weather'] = df_clean['Weather'].fillna('none')\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna('none')\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna('none')\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna('none')\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna('none')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_Q1_data):\n", + " duplicates = df_Q1_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q1_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q1_data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# checking categorical columns\n", + "categorical_cols = df_Q1_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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_Q1_data[col] = le.fit_transform(df_Q1_data[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_Q1_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df_Q1_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Weather\", \"Traffic_Level\")\n", + "numerical_cols = df_Q1_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop (\"Time_of_Day\", \"Vehicle_Type\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_Q1_data[numerical_cols] = scaler.fit_transform(df_Q1_data[numerical_cols])\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "df_Q1_data['Weather'].hist()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1_data['Traffic_Level'].hist()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1_data['Vehicle_Type'].hist()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean[cols] #here i couldnt remove orderid but the idea is ill split them and and start training the model and ill use\n", + "y = df_clean['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "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", + "#id use Kfold and eval mae and get av score\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(\"MAE :\", mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/342/Q2.ipynb b/submissions_extracted/342/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff855d0164fc6cbc8fea4f252a3c432c8e1c3e56 --- /dev/null +++ b/submissions_extracted/342/Q2.ipynb @@ -0,0 +1,334 @@ +{ + "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\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", + "import torch\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", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "X_train = torch.tensor(X_train.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", + "\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", + "\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(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + " plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN34Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\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", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/342/Q3.ipynb b/submissions_extracted/342/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f140f1bd4839ba3894ae0c91e4ea0e9a5955384b --- /dev/null +++ b/submissions_extracted/342/Q3.ipynb @@ -0,0 +1,212 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\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", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.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 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", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\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", + " df[target_column].hist()\n", + " plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "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/343/Q1.ipynb b/submissions_extracted/343/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4a8c76da1acc52307cdda2cf450ccd627aa28e80 --- /dev/null +++ b/submissions_extracted/343/Q1.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/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\n", + "import pandas as pd\n", + "\n", + "path = \"/kaggle/input/q1-exam-data/Q1_data.csv\"\n", + "df = pd.read_csv(path)\n", + "\n", + "print()\n", + "print(df.columns)\n", + "\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": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "df.columns = df.columns.str.strip()\n", + "\n", + "plt.hist(df['delivery_time'], bins=20, color='blue', edgecolor='black')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df.drop('Order_ID', axis=1, inplace=True)\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(df.isnull().sum())\n", + "\n", + "df.dropna(inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.drop_duplicates(inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df = pd.get_dummies(df)\n", + "\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "features = df.drop('delivery_time', axis=1)\n", + "df_scaled = pd.DataFrame(scaler.fit_transform(features), columns=features.columns)\n", + "\n", + "\n", + "df_scaled['delivery_time'] = df['delivery_time'].values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "plt.hist(df['delivery_time'])\n", + "print(\"Target is checked for distribution.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_scaled.drop('delivery_time', axis=1)\n", + "y = df_scaled['delivery_time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=100, 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.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", + "print(f\"Average MAE: {np.mean(mae_scores)}\")\n" + ], + "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", + "\n", + "importances = model.feature_importances_\n", + "feature_names = X.columns\n", + "feature_importance_df = pd.Series(importances, index=feature_names).sort_values(ascending=True)\n", + "\n", + "feature_importance_df.plot(kind='barh', color='teal')\n", + "plt.title('Feature Importance')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(predictions, bins=20, color='orange', edgecolor='black', alpha=0.7)\n", + "plt.title('Distribution of Predicted Delivery Time')\n", + "plt.xlabel('Predicted Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "from catboost import CatBoostRegressor\n", + "\n", + "mae_ensemble_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", + "\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " cb_model = CatBoostRegressor(silent=True, random_state=42)\n", + "\n", + " rf_model.fit(X_train, y_train)\n", + " cb_model.fit(X_train, y_train)\n", + "\n", + "\n", + " rf_preds = rf_model.predict(X_test)\n", + " cb_preds = cb_model.predict(X_test)\n", + " avg_preds = (rf_preds + cb_preds) / 2\n", + "\n", + " mae_ensemble_scores.append(mean_absolute_error(y_test, avg_preds))\n", + "\n", + "print(f\"Average Ensemble MAE: {np.mean(mae_ensemble_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/343/Q2.ipynb b/submissions_extracted/343/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c410cd055c43387c6d8fb7aea513dfc0557b705b --- /dev/null +++ b/submissions_extracted/343/Q2.ipynb @@ -0,0 +1,298 @@ +{ + "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 DataLoader, TensorDataset\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# 1.Convert Numpy arrays to PyTorch Tensors\n", + "X_train_tensor = torch.from_numpy(X_train).float()\n", + "X_test_tensor = torch.from_numpy(X_test).float()\n", + "y_train_tensor = torch.from_numpy(y_train).float().view(-1, 1)\n", + "y_test_tensor = torch.from_numpy(y_test).float().view(-1, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "print(f\"Images batch shape: {images.shape}\")\n", + "print(f\"Labels batch shape: {labels.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(4):\n", + " plt.subplot(1, 4, i+1)\n", + "\n", + " plt.imshow(images[i].permute(1, 2, 0))\n", + " plt.title(f\"Age: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "\n", + "class AgeModel(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgeModel, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.layers = nn.Sequential(\n", + " nn.Linear(input_size, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 64),\n", + " nn.ReLU(),\n", + " nn.Linear(64, 1)\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " return self.layers(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_loop(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for X, y in loader:\n", + " X, y = X.to(device), y.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(X)\n", + " loss = criterion(outputs, y)\n", + " loss.backward()\n", + " optimizer.step()\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def val_loop(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for X, y in loader:\n", + " X, y = X.to(device), y.to(device)\n", + " outputs = model(X)\n", + " loss = criterion(outputs, y)\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)\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", + " (Channels * Height * Width)\n", + "input_dim = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "\n", + "model = AgeModel(input_dim).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " t_loss = train_loop(model, train_loader, criterion, optimizer, device)\n", + " v_loss = val_loop(model, test_loader, criterion, device)\n", + " train_losses.append(t_loss)\n", + " val_losses.append(v_loss)\n", + " print(f\"Epoch {epoch+1:02d}: Train Loss = {t_loss:.4f}, Val Loss = {v_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Val Loss')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "plt.title('Training and Validation Loss')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " images, labels = next(iter(test_loader))\n", + " preds = model(images.to(device))\n", + "\n", + " plt.figure(figsize=(15, 6))\n", + " for i in range(5):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.imshow(images[i].permute(1, 2, 0))\n", + " plt.title(f\"Actual: {labels[i].item()}\\nPred: {preds[i].item():.1f}\")\n", + " plt.axis('off')\n", + " plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/343/Q3.ipynb b/submissions_extracted/343/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a3916e472a2df90c4683dd0b6c07b354a26f69be --- /dev/null +++ b/submissions_extracted/343/Q3.ipynb @@ -0,0 +1,244 @@ +{ + "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(os.path.join(path, \"Q3_data.csv\"))" + ], + "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 1: Write your code here:\n", + "df = df.fillna(df.mean(numeric_only=True))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Encode categorical variables (CatBoost)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Apply feature scaling (StandardScaler)\n", + "scaler = StandardScaler()\n", + "features_to_scale = df.drop(columns=['target']).columns\n", + "df[features_to_scale] = scaler.fit_transform(df[features_to_scale])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "Check for target imbalance\n", + "target_counts = df['target'].value_counts()\n", + "print(\"Target Balance:\\n\", target_counts)\n", + "is_imbalanced = target_counts.iloc[0] / target_counts.iloc[1] > 2\n", + "print(f\"Is imbalanced? {is_imbalanced}\")" + ], + "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", + "X = df.drop(columns=['target'])\n", + "y = df['target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "Print the averaged score across all folds\n", + "print(f\"Average F1 Score across all folds: {np.mean(scores):.4f}\")\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# Task 2: Use StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Task 3: Train a CatBoostClassifier\n", + "scores = []\n", + "\n", + "for train_index, val_index in skf.split(X, y):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + "\n", + " model = CatBoostClassifier(iterations=500, learning_rate=0.1, depth=6, silent=True)\n", + " model.fit(X_train, y_train)\n", + "\n", + "\n", + " preds = model.predict(X_val)\n", + " score = f1_score(y_val, preds)\n", + " scores.append(score)\n", + "\n", + "# Task 5: Print the averaged score across all folds\n", + "print(f\"Average F1 Score across all folds: {np.mean(scores):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Plot feature importance\n", + "feature_importance = model.get_feature_importance()\n", + "sorted_idx = np.argsort(feature_importance)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(X.columns[sorted_idx], feature_importance[sorted_idx])\n", + "plt.xlabel(\"CatBoost Feature Importance\")\n", + "plt.title(\"Feature Importance to find the Golden Feature\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Identify and print the 'golden feature'\n", + "golden_feature = X.columns[sorted_idx[-1]]\n", + "print(f\"The Golden Feature is: {golden_feature}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Task 1: Create new X with only the golden feature\n", + "X_golden = df[[golden_feature]]\n", + "\n", + "# Task 2: Run the same KFold loop with this single feature\n", + "golden_scores = []\n", + "for train_index, val_index in skf.split(X_golden, y):\n", + " X_t, X_v = X_golden.iloc[train_index], X_golden.iloc[val_index]\n", + " y_t, y_v = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " g_model = CatBoostClassifier(iterations=500, silent=True)\n", + " g_model.fit(X_t, y_t)\n", + "\n", + " g_preds = g_model.predict(X_v)\n", + " golden_scores.append(f1_score(y_v, g_preds))\n", + "\n", + "# Task 3: Print and compare the accuracy\n", + "full_model_avg = np.mean(scores)\n", + "golden_model_avg = np.mean(golden_scores)\n", + "\n", + "print(f\"Full Model F1 Score: {full_model_avg:.4f}\")\n", + "print(f\"Golden Feature Only F1 Score: {golden_model_avg:.4f}\")\n", + "print(f\"Performance Retained: {(golden_model_avg/full_model_avg)*100:.2f}%\")\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/344/Q1.ipynb b/submissions_extracted/344/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..60ecd10aad7b2ac07432bede96ab69318d697b04 --- /dev/null +++ b/submissions_extracted/344/Q1.ipynb @@ -0,0 +1,276 @@ +{ + "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", + "# Load the dataset\n", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()\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", + "\n", + "# Check data types and structure\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Descriptive statistics for numerical columns\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n", + "df.columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df= df.dropna(subset=numeric_cols)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\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 MinMaxScaler\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = MinMaxScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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", + "feature_cols = [\"Order_ID\",\t\"Distance_km\",\t\"Weather\"\t,\"Traffic_Level\"\t,\"Time_of_Day\"\t,\"Vehicle_Type\"\t,\"Preparation_Time_min\"\t,\"Courier_Experience_yrs\"\t]\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "for train_idx, val_idx in kfold.split(X):\n", + " X_fold_train, X_fold_val = X[train_idx], X[val_idx]\n", + " y_fold_train, y_fold_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\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", + "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 2,3,4,5: Write your code here:\n", + "\n", + " # Train and predict\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_fold_train, y_fold_train)\n", + "y_fold_pred = model.predict(X_fold_val)" + ], + "execution_count": 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/344/Q2.ipynb b/submissions_extracted/344/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fda10fa69fbc7c94e6216b04a4edc191d4c7bf91 --- /dev/null +++ b/submissions_extracted/344/Q2.ipynb @@ -0,0 +1,355 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# DataLoader for training data\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Get the first fold's split\n", + "for train_index, test_index in skf.split(X, y):\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + " break # Use only the first split\n", + "\n", + "# 1. Convert to Tensors\n", + "X_train_tensor = torch.tensor(X_train.values, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32).unsqueeze(1) # Add a dimension for binary classification\n", + "X_test_tensor = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32).unsqueeze(1)\n", + "\n", + "print(\"Tensor Shapes:\")\n", + "print(f\"X_train_tensor: {X_train_tensor.shape}\")\n", + "print(f\"y_train_tensor: {y_train_tensor.shape}\")\n", + "print(f\"X_test_tensor: {X_test_tensor.shape}\")\n", + "print(f\"y_test_tensor: {y_test_tensor.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create Datasets\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "print(\"\\nNumber of samples in datasets:\")\n", + "print(f\"Train dataset: {len(train_dataset)}\")\n", + "print(f\"Test dataset: {len(test_dataset)}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "batch_size = 32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# 4. Inspect Data: Print the shape of one batch from the train loader\n", + "print(\"\\nInspecting one batch from train_loader:\")\n", + "for features_batch, labels_batch in train_loader:\n", + " print(f\"Features Batch Shape: {features_batch.shape}\")\n", + " print(f\"Labels Batch Shape: {labels_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + " # 5. Display a few samples (adapting 'display images' for tabular data)\n", + " print(\"\\nFirst 5 samples from the batch:\")\n", + " print(\"Features:\\n\", features_batch[:5])\n", + " print(\"Labels:\\n\", labels_batch[:5])\n", + " break # Only inspect the first batch\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "from tqdm.auto import tqdm\n", + "\n", + "def train_epoch(model, data_loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for batch_idx, (inputs, labels) in enumerate(tqdm(data_loader, desc=\"Training\")):\n", + " inputs, labels = inputs.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + "\n", + " outputs = model(inputs)\n", + " loss = loss_fn(outputs, labels)\n", + "\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " avg_loss = total_loss / len(data_loader)\n", + " return avg_loss\n", + "\n", + "print(\"train_epoch function defined successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "from tqdm.auto import tqdm\n", + "\n", + "def validate_epoch(model, data_loader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for batch_idx, (inputs, labels) in enumerate(tqdm(data_loader, desc=\"Validation\")):\n", + " inputs, labels = inputs.to(device), labels.to(device)\n", + "\n", + " outputs = model(inputs)\n", + " loss = loss_fn(outputs, labels)\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " avg_loss = total_loss / len(data_loader)\n", + " return avg_loss\n", + "\n", + "print(\"validate_epoch function defined successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.optim as optim\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "# 1. Set Device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# Hyperparameters for dummy data and training\n", + "INPUT_SIZE = 10\n", + "OUTPUT_SIZE = 1\n", + "NUM_EPOCHS = 20\n", + "BATCH_SIZE = 32\n", + "LEARNING_RATE = 0.001\n", + "\n", + "# 2. Model Initialization\n", + "model = SimpleNN(input_size=INPUT_SIZE, output_size=OUTPUT_SIZE).to(device)\n", + "print(f\"Model initialized and moved to {device}.\")\n", + "\n", + "# 3. Loss Function\n", + "loss_fn = nn.MSELoss()\n", + "print(\"Loss function (MSELoss) defined.\")\n", + "\n", + "# 4. Optimizer\n", + "optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\n", + "print(\"Optimizer (Adam) defined.\")\n", + "\n", + "# 6. Data Generation (Dummy Data)\n", + "# Generate random dummy data for training\n", + "X_train = torch.randn(1000, INPUT_SIZE)\n", + "y_train = torch.randn(1000, OUTPUT_SIZE)\n", + "\n", + "# Generate random dummy data for validation\n", + "X_val = torch.randn(200, INPUT_SIZE)\n", + "y_val = torch.randn(200, OUTPUT_SIZE)\n", + "\n", + "# Create TensorDatasets\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "val_dataset = TensorDataset(X_val, y_val)\n", + "\n", + "# Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n", + "val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False)\n", + "print(\"Dummy training and validation data loaders created.\")\n", + "\n", + "# 7. Training Loop\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"\\nStarting main training and validation loop...\")\n", + "for epoch in range(NUM_EPOCHS):\n", + " avg_train_loss = train_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " avg_val_loss = validate_epoch(model, val_loader, loss_fn, device)\n", + "\n", + " train_losses.append(avg_train_loss)\n", + " val_losses.append(avg_val_loss)\n", + "\n", + " print(f\"Epoch {epoch+1}/{NUM_EPOCHS}: Train Loss = {avg_train_loss:.4f}, Val Loss = {avg_val_loss:.4f}\")\n", + "\n", + "# 8. Summarize Results\n", + "final_train_loss = train_losses[-1]\n", + "final_val_loss = val_losses[-1]\n", + "\n", + "print(\"\\nTraining and validation complete!\")\n", + "print(f\"Final Training Loss: {final_train_loss:.4f}\")\n", + "print(f\"Final Validation Loss: {final_val_loss:.4f}\")" + ], + "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/344/Q3.ipynb b/submissions_extracted/344/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1448f5cbe38239eef0712a41ff8cb8952b89254e --- /dev/null +++ b/submissions_extracted/344/Q3.ipynb @@ -0,0 +1,212 @@ +{ + "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", + "path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "\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", + "\n", + "# Check data types and structure\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Descriptive statistics for numerical columns\n", + "df.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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "features = df.columns.drop(\"Target\")\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:" + ], + "execution_count": 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/345/Q1.ipynb b/submissions_extracted/345/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a6581cd29ead10ea499684704a3f70fa675ead58 --- /dev/null +++ b/submissions_extracted/345/Q1.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Read the dataset (Q1_data.csv) using read_csv()\n", + "\n", + "q1_path= os.path.join(path, 'Q1_data.csv')\n", + "df_q1= pd.read_csv(q1_path)\n", + "\n", + "print(f\"Shape: {df_q1.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# read heads\n", + "df_q1.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# info data\n", + "\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=30, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('Attack')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# im gonna drop the 'Order_ID' column from the data\n", + "df_q1 = df_q1.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# missing values\n", + "df_q1.isnull().sum()\n", + "\n", + "num_cols = df_q1.select_dtypes(include=['number']).columns\n", + "df_q1[num_cols] = df_q1[num_cols].fillna(df_q1[num_cols].median())\n", + "\n", + "cat_cols = df_q1.select_dtypes(exclude=['number']).columns\n", + "for col in cat_cols:\n", + " df_q1[col] = df_q1[col].fillna(df_q1[col].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# check duplicates and remove if there any\n", + "print(\"Checking for duplicate rows...\")\n", + "\n", + "duplicate_rows = df_q1.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_q1 = df_q1.drop_duplicates()\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", + "# ncode categorical variables if needed (Bonus if used One Hot Encoding\n", + "categorical_cols = df_q1.select_dtypes(include=['object']).columns\n", + "df_q1 = pd.get_dummies(df_q1, columns=categorical_cols)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "X = df_q1.drop(columns=['Delivery_Time'])\n", + "y = df_q1['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# i forget how to solve it, but im gonna try pls be kind with me ^.^\n", + "# no need to do imbalanced(inshallah) XD\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop(columns=['Delivery_Time'])\n", + "y = df_q1['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + " # id\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_cols = stat_cols + ['Delivery_Time', 'Courier_Experience_yrs', 'Preparation_Time_min']\n", + "\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot predicted delivery time histogram\n", + "\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel('Predicted Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Predicted Delivery Time Distribution')\n", + "plt.show()\n", + "\n", + "\n", + "\n", + "\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/345/Q2.ipynb b/submissions_extracted/345/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e57c3476ecb9ec6bb9875b6bbcb4a80aef2a4a02 --- /dev/null +++ b/submissions_extracted/345/Q2.ipynb @@ -0,0 +1,239 @@ +{ + "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", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "# 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", + "import torch\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_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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "for X_batch, y_batch in train_loader:\n", + " print(X_batch.shape, y_batch.shape)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].permute(1, 2, 0))\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "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", + "\n", + "\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\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/345/Q3.ipynb b/submissions_extracted/345/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..136a22073f0ff3d83575d91406ee14f400bac996 --- /dev/null +++ b/submissions_extracted/345/Q3.ipynb @@ -0,0 +1,206 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, 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", + "\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 data\n", + "# Load the CSV file\n", + "q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df_q3= pd.read_csv(q3_path)\n", + "print(f\"Shape: {df_q3.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# print head\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# missing values\n", + "\n", + "print(\"Missing values:\")\n", + "print(df_q3.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\"Checking for duplicate rows...\")\n", + "\n", + "duplicate_rows = df_q3.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_q1 = df_q3.drop_duplicates()\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", + "\n", + "\n", + "cat_cols = df_q3.select_dtypes(include=['object']).columns\n", + "df_q3 = pd.get_dummies(df_q3, columns=cat_cols, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "X = df_q1.drop(columns=['P_2'])\n", + "y = df_q1['P_2']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": 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/346/Q1.ipynb b/submissions_extracted/346/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..240b7a5343e6ca6e98e0808fd86d87b123b36aee --- /dev/null +++ b/submissions_extracted/346/Q1.ipynb @@ -0,0 +1,287 @@ +{ + "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", + "warnings.filterwarnings('ignore')\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", + "delivery_time = os.path.join(path, 'Q1_data.csv')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery = pd.read_csv(delivery_time)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(f\"Dataset shape: {df_delivery.shape}\")\n", + "df_delivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_delivery[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in [ 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "df_clean['Order_ID'] = df_clean['Order_ID'].fillna(df_clean['Order_ID'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', '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": [ + "# Task 5: Write your code here:\n", + "# Car age: older cars typically worth less\n", + "df_clean['Order_ID'] = 2026 - df_clean['Distance_km']\n", + "\n", + "# Mileage per year: high usage = more wear\n", + "df_clean['miles_per_year'] = df_clean['Traffic_Level'] / (df_clean['Order_ID'])\n", + "\n", + "\n", + "# Interaction: captures combined effect of age and annual mileage\n", + "df_clean['age_x_miles_per_year'] = df_clean['miles_per_year'] * df_clean['Order_ID']\n", + "\n", + "# Quick preview of engineered features\n", + "df_clean[['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']].head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "condition_counts = df_delivery['Distance_km'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(condition_counts.index, condition_counts.values, color='coral')\n", + "plt.title('Distance_km Distribution')\n", + "plt.xlabel('Distance_km')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "X = df_delivery[feature_cols]\n", + "y = df_clean['Weather']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "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_cars['Distance_km'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Distance_km Distribution')\n", + "plt.xlabel('Distance_km')\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_cars['Delivery_Time'].dropna(), bins=50, edgecolor='black', color='green')\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/346/Q2.ipynb b/submissions_extracted/346/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..525fbe59df52b611b0f1e186001c0318a44c455d --- /dev/null +++ b/submissions_extracted/346/Q2.ipynb @@ -0,0 +1,411 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "x = torch.randn(1600, 3, 36, 36)\n", + "x_train = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_train.shape)\n", + "\n", + "x = torch.randn(400, 3, 36, 236)\n", + "x_test = x.squeeze()\n", + "print(\"Squeeze:\", x_test.shape)\n", + "\n", + "\n", + "x = torch.randn(3, 28, 28)\n", + "y_train = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", y_train.shape)\n", + "\n", + "\n", + "x = torch.randn(32, 28, 28, 3)\n", + "y_test = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", y_test.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " 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", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " a4 = self.relu(z4)\n", + "\n", + " return a4\n", + "\n", + "\n", + "\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", + " # 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", + "\n", + "# Model parameters\n", + "\n", + "input_dim = 3 * 32 * 32\n", + "\n", + "\n", + "hidden_dim = 64\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10\n", + "\n", + "\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "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/346/Q3.ipynb b/submissions_extracted/346/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..64a8940b8379a0e5d9a7061535fadb25edc2bb23 --- /dev/null +++ b/submissions_extracted/346/Q3.ipynb @@ -0,0 +1,247 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "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", + "golden_path = os.path.join(path, 'Q3_data.csv')\n", + "df_golden = pd.read_csv(golden_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_golden.shape}\")\n", + "df_golden.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_golden.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_golden.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']\n", + "df_clean = df_golden[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['B_39'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in ['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n", + "df_clean['D_87'] = df_clean['D_87'].fillna(df_clean['D_87'].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", + "categorical_cols = ['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_clean['D_87'] = 2026 - df_clean['B_39']\n", + "\n", + "# Mileage per year: high usage = more wear\n", + "df_clean['D_111'] = df_clean['D_88'] / (df_clean['D_87'])\n", + "\n", + "\n", + "# Interaction: captures combined effect of age and annual mileage\n", + "df_clean['D_136'] = df_clean['D_73'] * df_clean['D_87']\n", + "\n", + "# Quick preview of engineered features\n", + "df_clean[['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']].head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_golden['golden_feature'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('golden_feature Distribution')\n", + "plt.xlabel('golden_feature')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']\n", + "X = df_golden[feature_cols]\n", + "y = df_clean['Weather']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\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/347/Q1.ipynb b/submissions_extracted/347/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5a44a69df3f1bb8ba03334887bb04c4bb38f60d --- /dev/null +++ b/submissions_extracted/347/Q1.ipynb @@ -0,0 +1,334 @@ +{ + "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", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\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", + "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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID', axis = 1)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df.dropna(subset = ['Weather', 'Traffic_Level','Time_of_Day','Courier_Experience_yrs', 'Delivery_Time']).copy()\n", + "#df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\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", + "\n", + "df_clean.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " # Task 4: Write your code here:\n", + "cat_cols = ['Weather', 'Time_of_Day', 'Vehicle_Type','Traffic_Level']\n", + "for col in cat_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": [ + "df_clean.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\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", + "print(\"It's clear there is no significant imbalance\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "x = df_clean[df_clean.columns.drop(\"Delivery_Time\")]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "predicted = []\n", + "losses = []\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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", + " print(1)\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + " predicted.append(y_pred)\n", + "\n", + " losses.append(mse)\n", + "print(losses)\n", + "\n", + "\n", + "print(predicted)\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': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "predicted['Delivery_Time'].hist(bins = 30, edgecolor = 'black')\n", + "\n", + "plt.title(f\"predictions\")\n", + "plt.xlabel('Delivery_Time predictions')\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/347/Q2.ipynb b/submissions_extracted/347/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0206ba0fa1740a0255d60b4abc1fc5b75116727 --- /dev/null +++ b/submissions_extracted/347/Q2.ipynb @@ -0,0 +1,384 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train)\n", + "X_test = torch.tensor(X_test)\n", + "\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 TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_dataset = TensorDataset(X_train,y_train)\n", + "test_dataset = TensorDataset(X_test,y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\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, # we don't shuffle test data\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + " # Layer 1\n", + " z1 = self.layer1(x).to_dtype('float32')\n", + " a1 = self.relu(z1).to_dtype('float32')\n", + " # layer2\n", + " z2 = self.layer2(a1).to_dtype('float32')\n", + " a2 = self.relu(z2).to_dtype('float32')\n", + " # layer 3\n", + " z3 = self.layer3(a2).to_dtype('float32')\n", + " a3 = self.relu(z3).to_dtype('float32')\n", + "\n", + " # output layer\n", + " z4 = self.layer4(a3).to_dtype('float32')\n", + " return z4\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).to_dtype('float32')\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\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", + " 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", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 64\n", + "output_dim = 1 # we are predicting age ---> one output\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\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", + "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).to_dtype('float32')\n", + " print(1)\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", + "#no idea what exactly is causing this error." + ], + "execution_count": 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/347/Q3.ipynb b/submissions_extracted/347/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a26400a17175917f649c88b7740df8768b9acaa3 --- /dev/null +++ b/submissions_extracted/347/Q3.ipynb @@ -0,0 +1,256 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "pathhh = os.path.join(path, 'Q3_data.csv')\n", + "print(\"Path to dataset files:\", path)\n", + "df = pd.read_csv(pathhh)\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", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "# There is a problem with .info(). I will just fill all with unknown\n", + "\n", + "\n", + "df = df.fillna('uknown')\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "df.select_dtypes(include=[\"object\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "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:" + ], + "execution_count": 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/348/Q1.ipynb b/submissions_extracted/348/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f7370b160c72c992de3dfcdc356064fa74381eb1 --- /dev/null +++ b/submissions_extracted/348/Q1.ipynb @@ -0,0 +1,338 @@ +{ + "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\n", + "from catboost import CatBoostRegressor\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", + "actual_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(actual_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "display(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", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=['Order_ID'])" + ], + "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", + "display(missing_data)\n", + "\n", + "df = df.dropna(subset=['Delivery_Time']) # Rows with missing target variable should be dropped because we can't predict with them.\n", + "\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df['Courier_Experience_yrs'].mean())\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "catcols = ['Weather', 'Time_of_Day', \"Vehicle_Type\", \"Traffic_Level\"]\n", + "for col in catcols:\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", + "features = df.columns.drop(\"Delivery_Time\") # We don't want to 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", + "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()\n", + "\n", + "print(\"\\nThe target roughly has a normal distribution with a very slight positive skew\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = [\"Distance_km\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\", \"Preparation_Time_min\", \"Courier_Experience_yrs\"]\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "preds = []\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", + " print(f\"Training Random Forest...\")\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", + " preds.append(y_pred)\n", + "\n", + "total = 0\n", + "for score in mae_scores:\n", + " total+=score\n", + "my_mean = total/len(mae_scores)\n", + "\n", + "print(f\"Averaged MAE Score: {my_mean:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " plt.hist(preds, bins=10)\n", + " plt.title(f\"Predicted Delivery Time Distribution\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\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", + "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", + " # 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}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/348/Q2.ipynb b/submissions_extracted/348/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..25cde83a656bed6a2639343d04625b7cd5730c58 --- /dev/null +++ b/submissions_extracted/348/Q2.ipynb @@ -0,0 +1,366 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "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", + "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", + "# 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", + "\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", + " # 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", + " 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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 36 * 36 # images flattened\n", + "hidden_dim = 16 # Design choice\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, 1).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", + "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/348/Q3.ipynb b/submissions_extracted/348/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7b78cdcbc99462d9b074f51757d77530634c9cca --- /dev/null +++ b/submissions_extracted/348/Q3.ipynb @@ -0,0 +1,270 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "%matplotlib inline\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pathpath = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(pathpath)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "display(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", + "for col in df.columns:\n", + " df[col] = df[col].fillna(df[col].mean())\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))\n", + "\n", + "# No need to encode any categorical columns because there aren't any" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "ss = StandardScaler()\n", + "cols_to_scale = df.columns.drop(\"Target\")\n", + "\n", + "for column in cols_to_scale:\n", + " df[column] = ss.fit_transform(df[[column]])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"Default: {df['Target'].sum()}\")\n", + "print(f\"No Default: {(df['Target'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = cols_to_scale = df.columns.drop(\"Target\")\n", + "X = df[feature_cols]\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "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", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "all_results = {}\n", + "\n", + "all_results[\"Catboost\"] = {'accuracy': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn model\n", + " print(f\"Training Catboost...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[\"Catboost\"]['accuracy'].append(accuracy)\n", + " all_results[\"Catboost\"]['f1'].append(f1)\n", + "\n", + "print(f\" Accuracy: {np.mean(all_results[\"Catboost\"]['accuracy']):.4f}\")\n", + "print(f\" F1-Score: {np.mean(all_results[\"Catboost\"]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n", + "\n", + "golden_feature = feature_importance.sort_values('importance', ascending=False).iloc[0, 0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"The golden feature is {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/349/Q1.ipynb b/submissions_extracted/349/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e23ceb8984b388eb3aef461a0516e3401054341e --- /dev/null +++ b/submissions_extracted/349/Q1.ipynb @@ -0,0 +1,347 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "import seaborn as sns\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + "\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", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "print(missing_percentage)\n", + "df = df.dropna()" + ], + "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 = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " 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", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np # for random data generation\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "import pandas as pd\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + "\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", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "feature_cols = [\"Delivery Time\"]\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/349/Q2.ipynb b/submissions_extracted/349/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..01aa893f70d25df8d6c447ccec28113b66d2b122 --- /dev/null +++ b/submissions_extracted/349/Q2.ipynb @@ -0,0 +1,397 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "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", + "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", + "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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 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", + "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", + "from torch.optim import AdamW\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", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 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", + "\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", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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", + "import numpy as np\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "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/349/Q3.ipynb b/submissions_extracted/349/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e179409fe64943a763924fc6b6e22e76766e720 --- /dev/null +++ b/submissions_extracted/349/Q3.ipynb @@ -0,0 +1,284 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\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_percentage = (df.isnull().sum() / len(df)) * 100\n", + "print(missing_percentage)\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", + " for col in df:\n", + " df[col].fillna(df[col].mean())\n", + " print(\"Missing values remaining:\", df.isnull().sum().sum())\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\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", + "#there isnt a need to encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\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", + "#our data imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = \"Target\"\n", + "\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np # for random data generation\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + "" + ], + "execution_count": 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/35/Q1.ipynb b/submissions_extracted/35/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fed25ca81a932120053e655ad3f27026811a6539 --- /dev/null +++ b/submissions_extracted/35/Q1.ipynb @@ -0,0 +1,202 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#قراءة البيانات\n", + "df = pd.read_csv(path + \"/diamonds.csv\")\n", + "df = df.drop('Unnamed: 0', axis=1)\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", + "delivery_time= df.select_dtypes(include=['object']).columns" + ], + "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 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/35/Q2.ipynb b/submissions_extracted/35/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/35/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/35/Q3.ipynb b/submissions_extracted/35/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3d4e140aba075ea73c86119924abc8f7add37725 --- /dev/null +++ b/submissions_extracted/35/Q3.ipynb @@ -0,0 +1,334 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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 4: Write your code here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": 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": [ + "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 2,3,4,5: Write your code 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 1: Write your code here: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 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/350/Q1.ipynb b/submissions_extracted/350/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..aaa229e1de270263321519655f133adea9c7d1cd --- /dev/null +++ b/submissions_extracted/350/Q1.ipynb @@ -0,0 +1,262 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=25, edgecolor='black')\n", + "plt.title('DeliveryTime')\n", + "plt.xlabel('Minutes')\n", + "plt.ylabel('PreparationTime')\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", + "df.dropna(subset=['Delivery_Time'])\n", + "\n", + "df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"\\n6. DUPLICATE ROWS: {duplicates}\")\n", + "df.drop_duplicates(inplace=True)\n", + "\n", + "missing = df.isnull().sum()\n", + "missing_percent = (missing / len(df)) * 100\n", + "missing_df = pd.DataFrame({'Missing': missing, 'Percent': missing_percent})\n", + "print(missing_df[missing_df['Missing'] > 0].sort_values('Percent', ascending=False))\n", + "\n", + "df = df.dropna(axis=1, thresh=len(df)*0.5)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = label_encoder.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "print('data before scaling:\\n', df )\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X = df.drop('Delivery_Time', axis=1)\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 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=100, max_depth=20, random_state=42, n_jobs=-1)\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=25, edgecolor='black')\n", + "plt.title('DeliveryTime')\n", + "plt.xlabel('Minutes')\n", + "plt.ylabel('PreparationTime')\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/350/Q2.ipynb b/submissions_extracted/350/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d8e670a1c8e6796e28c0b069efc630680e175bb2 --- /dev/null +++ b/submissions_extracted/350/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", + "\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", + "\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", + "\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "\n", + "train_ds = TensorDataset(X_train, y_train)\n", + "test_ds = TensorDataset(X_test, y_test)\n", + "\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", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "x = torch.randn(4, 3)\n", + "\n", + "y = linear(x)\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch.nn.functional as F\n", + "class TabularNN(nn.Module):\n", + " def __init__(self, input_size, hidden_size, num_classes):\n", + " super(TabularNN, self).__init__()\n", + " # Layer 1: Input to Hidden\n", + " self.fc1 = nn.Linear(input_size, hidden_size)\n", + " # Layer 2: Hidden to Hidden\n", + " self.fc2 = nn.Linear(hidden_size, hidden_size)\n", + " # Layer 3: Hidden to Output\n", + " self.fc3 = nn.Linear(hidden_size, num_classes)\n", + "\n", + " self.dropout = nn.Dropout(0.2) # Optional: prevents overfitting\n", + "\n", + " def forward(self, x):\n", + " x = F.relu(self.fc1(x)) # Activation 1\n", + " x = self.dropout(x) # Apply dropout\n", + " x = F.relu(self.fc2(x)) # Activation 2\n", + " # NOTE: No Softmax here if using CrossEntropyLoss!\n", + " x = self.fc3(x)\n", + " return x\n", + "\n", + "import torch.nn as nn\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = TabularNN(input_size=X_train.shape[1], hidden_size=64, num_classes=len(y)).to(device)\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\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", + " model.train() # Set to training mode\n", + " train_loss = 0\n", + "\n", + " for batch_X, batch_y in train_loader:\n", + " batch_X, batch_y = batch_X.to(device), batch_y.to(device)\n", + "\n", + " # Standard 5-step process:\n", + " optimizer.zero_grad() # 1. Reset gradients\n", + " outputs = model(batch_X) # 2. Forward pass\n", + " loss = criterion(outputs, batch_y) # 3. Calculate loss\n", + " loss.backward() # 4. Backward pass\n", + " optimizer.step() # 5. Update weights\n", + "\n", + " train_loss += loss.item()\n", + "\n", + "model.eval() # Set to evaluation mode\n", + "correct = 0\n", + "total = 0\n", + "with torch.no_grad(): # Disable gradient tracking (saves memory)\n", + " for batch_X, batch_y in test_loader:\n", + " batch_X, batch_y = batch_X.to(device), batch_y.to(device)\n", + " outputs = model(batch_X)\n", + " _, predicted = torch.max(outputs, 1) # Get class with highest logit\n", + " total += batch_y.size(0)\n", + " correct += (predicted == batch_y).sum().item()\n", + "\n", + "accuracy = 100 * correct / total\n", + "print(f\"Epoch {epoch+1}/{epochs} | Loss: {train_loss/len(train_loader):.4f} | Acc: {accuracy:.2f}%\")\n" + ], + "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_loss, label='Train Loss')\n", + "plt.plot(val_loss, 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/350/Q3.ipynb b/submissions_extracted/350/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2f56fd3d33066ccff6d868fb262e7b66a8d30158 --- /dev/null +++ b/submissions_extracted/350/Q3.ipynb @@ -0,0 +1,233 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pay_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(pay_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n2. FIRST 5 ROWS:\")\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 1: Write your code here:\n", + "missing = df.isnull().sum()\n", + "missing_percent = (missing / len(df)) * 100\n", + "missing_df = pd.DataFrame({'Missing': missing, 'Percent': missing_percent})\n", + "print(missing_df[missing_df['Missing'] > 0].sort_values('Percent', ascending=False))\n", + "\n", + "df = df.dropna(axis=1, thresh=len(df)*0.5)\n", + "\n", + "print(missing_df[missing_df['Missing'] > 0].sort_values('Percent', ascending=False))\n", + "df['D_77'].fillna(df['D_77'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"\\n6. DUPLICATE ROWS: {duplicates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "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:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot()\n", + "\n", + "plt.title('Golden feature')\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/351/Q1.ipynb b/submissions_extracted/351/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0f1263b955d5d19f6e879fd11a31a544269163a --- /dev/null +++ b/submissions_extracted/351/Q1.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/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", + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "#we have 1663 samples and 9 feutures" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# first 5 rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "# 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 Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "#From the plot below we can see that the target a litile reight skewed" + ], + "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", + "\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", + "#since the sample is mor than 1k, I will delete the missing valus for now.\n", + "#but if there some time we can try to impute them with mode for catogrical coloumn and see if this will make the model better\n", + "#impotentL: the missing target value must drop, we cannt predict somting missing\n", + "\n", + "df = df.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Do we have duplicate samples?\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "#LabelEncoder: used for ordnial data, but sometimes we need to use it\n", + "#even if the data is nominal, because if we use OneHotEncoder\n", + "#it will increes the number of dimnation and we may fall in problem calld\n", + "#curse of dimantionlty, so I will use it only for the Weather\n", + "\n", + "categorical_cols = ['Traffic_Level', 'Time_of_Day', 'Vehicle_Type','Weather']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "#somting go worng with it, If there is time I will come back and try to fix it\n", + "#for now I will do LabelEncoder only\n", + "#Weather_cat = ['Weather']\n", + "#oneHot = OneHotEncoder(sparse_output=False)\n", + "#df[Weather_cat] = oneHot.fit_transform(df[Weather_cat].astype(str))\n", + "\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # WE DON'T SCALE THE TARGET\n", + "numerical_cols = df[features].select_dtypes(include='number').columns\n", + "scaler = StandardScaler()\n", + "df[features] = 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", + "#we are working on linar regration problem so no need for that, If it is a classification we will use it." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "import numpy as np\n", + "# 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", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=40, max_depth=10, random_state=42, n_jobs=-1)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_mae = []\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " model.fit(X_train.values, y_train.values)\n", + "\n", + " # Validate\n", + " y_pred = model.predict(X_test.values)\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print('averaged score across all folds:', np.mean(np.array(mae)))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "# Retrieve Ridge coefficients and sort by absolute importance\n", + "\n", + "importance = list(zip(X.columns, model.feature_importances_))\n", + "sorted_importance = sorted(importance, key=lambda x: abs(x[1]), reverse=True)\n", + "\n", + "# Extract sorted features and their coefficients\n", + "features, coefficients = zip(*sorted_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, coefficients, color='darkblue')\n", + "plt.xlabel('Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=30, edgecolor='black', color='yellow')\n", + "plt.title('Delivery time histogram')\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/351/Q2.ipynb b/submissions_extracted/351/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..30ff460f8e4476f1e16be43288edbbb3f81f6a0d --- /dev/null +++ b/submissions_extracted/351/Q2.ipynb @@ -0,0 +1,412 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# 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": [ + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# 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}\")# 3. Create DataLoaders\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", + "\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) #i+1 --> يحدد مكان الصورة الحالية في الشبكة.\n", + " #we use premute because matplot need the shape like this (36,36,3)\n", + "\n", + " plt.imshow(images[i].permute(1,2,0), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn\n", + "\n", + "# 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", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + " output = self.layer4(a3) # we predicts the age of a person so last layer must be linear layer\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) #nn.MseLoss expext (N,1) not (N,)\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() #evaluation mode\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.view(-1, 1).to(device)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch) # shape: (batch_size, 1)\n", + " running_loss += loss.item() #return float number\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import AdamW\n", + "\n", + "# Task 4: Define device, model, loss, optimizer:\n", + "#Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 36*36*3 # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim,1).to(device)\n", + "\n", + "# Hyperparameters\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# 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", + "labels = labels.cpu()\n", + "predictions = outputs.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(20, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].permute(1,2,0), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i].item()}\") #first time when I print predictions, it give me torsh.tensor(number)\n", + " #so I thoght I need to use float ot return number\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/351/Q3.ipynb b/submissions_extracted/351/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5dd51f39b23e17ccb12d3912d0fbb71da80aa447 --- /dev/null +++ b/submissions_extracted/351/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", + "\n", + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# first 5 rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "#we can see the Missing_Percentage for some column is 99%!\n", + "#I don't see droping na is the right solotion here\n", + "#I will drop the entire column because too many values are missing\n", + "df= df.drop(columns=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Do we have duplicate samples?\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", + "# No need because from info above we can see thers is no Object type\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Task 4: Write your code here:\n", + "features = df.columns.drop(\"Target\") # WE DON'T SCALE THE TARGET\n", + "numerical_cols = df[features].select_dtypes(include='number').columns\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# 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\")\n", + "#we can see the our target is imbalance so we must use Stratification\n", + "#to forces the Train and Test splits to preserve the same class ratios as the original dataset." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\n" + ], + "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", + "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_accuracy = []\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", + " model = CatBoostClassifier(verbose=0,n_estimators=200,max_depth=4)\n", + "\n", + " # Train the model\n", + " model.fit(X_train, y_train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + "print(' averaged accuracy:',np.mean(np.array(lr_accuracy)))\n", + "print(' averaged f1: ',np.mean(np.array(lr_accuracy)))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "importance = list(zip(X.columns, model.feature_importances_))\n", + "sorted_importance = sorted(importance, key=lambda x: abs(x[1]), reverse=True)\n", + "\n", + "# Extract sorted features and their coefficients\n", + "features, coefficients = zip(*sorted_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(20, 15))\n", + "plt.barh(features, coefficients, color='darkblue')\n", + "plt.xlabel('Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"golden feature: 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/352/Q1.ipynb b/submissions_extracted/352/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3055f95849e64073a829faea4277c02dcc7cba87 --- /dev/null +++ b/submissions_extracted/352/Q1.ipynb @@ -0,0 +1,427 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#import important libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score" + ], + "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", + "print(df_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Delivery_Time distribution (target variable)\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('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean=df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping Order_ID {df_clean.shape}\")\n", + "print(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "# We can see that the missing percentage is low in the the columns which have missing values and we can handle it by droppping the rows with nan value without deleting the whole columns." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Drop NAN values\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n", + "print(f\"After dropping nan value rows {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#Check duplicates and drop them\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "for col in df_clean:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "feature_cols = [ 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "#Check for target imbalance and state if it is imbalanced or not.\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#Train a RandomForest regressor model\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 4: Write your code here:\n", + "\n", + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "# Predict and evaluate\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 5: Write your code here:\n", + "\n", + "#Print the averaged score across all folds\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_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", + "\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model.feature_importances_)\n", + "print(feature_cols)" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/352/Q2.ipynb b/submissions_extracted/352/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a3794dc56d090d4a8c8d510a89c25de1bcc8454b --- /dev/null +++ b/submissions_extracted/352/Q2.ipynb @@ -0,0 +1,431 @@ +{ + "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 important libraries\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" + ], + "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.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='Q2_data.csv', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='Q2_data.csv', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\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", + "# Create Dataloaders to train and test data in batches\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", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "plt.subplot(2, 3, 1)\n", + "plt.imshow(images[0].squeeze(), 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", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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", + "# 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", + "# 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", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/352/Q3.ipynb b/submissions_extracted/352/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8718c3ab38f757d1371304aa3db22024238ad82 --- /dev/null +++ b/submissions_extracted/352/Q3.ipynb @@ -0,0 +1,231 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "print(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_data.shape}\")\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()" + ], + "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", + "cols = ['Order_ID','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean=df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping Order_ID {df_clean.shape}\")\n", + "print(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "# We can see that the missing percentage is low in the the columns which have missing values and we can handle it by droppping the rows with nan value without deleting the whole columns.\n", + "\n", + "# Drop NAN values\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n", + "print(f\"After dropping nan value rows {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "for col in df_clean:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "feature_cols = [ 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "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:\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"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:" + ], + "execution_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/353/Q1.ipynb b/submissions_extracted/353/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7af881f8a8d1d8cfb88174fec3f3bda49755cc46 --- /dev/null +++ b/submissions_extracted/353/Q1.ipynb @@ -0,0 +1,265 @@ +{ + "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 matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dil_path = os.path.join(path, 'Q1_data.csv')\n", + "df_dil = pd.read_csv(dil_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df_dil.shape}\")\n", + "df_dil.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_dil.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_dil.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.hist(df_dil[\"Delivery_Time\"])\n", + "plt.xlabel(\"Y\")\n", + "plt.ylabel(\"X\")\n", + "plt.title(\"delivery_Time\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_dil = df_dil.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_dil = df_dil.dropna(subset=[\"Delivery_Time\"])\n", + "\n", + "df_dil[\"Courier_Experience_yrs\"] = df_dil[\"Courier_Experience_yrs\"].fillna(df_dil[\"Courier_Experience_yrs\"].median())\n", + "\n", + "for col in [\"Weather\", \"Traffic_Level\", \"Time_of_Day\"]:\n", + " df_dil[col] = df_dil[col].fillna(df_dil[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#### نشوف كم صف مكرر\n", + "dup=df_dil.duplicated().sum()\n", + "### نتحذف الصفوف المكرره اذا في\n", + "df_dil = df_dil.drop_duplicates()\n", + "print(dup)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "#### نحدد الأعمدة\n", + "cat_cols = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "#### نستخدم الonHotEncoding\n", + "preprocessor = ColumnTransformer(\n", + " transformers=[\n", + " (\"cat\", OneHotEncoder(drop=\"first\", sparse_output=False), cat_cols)\n", + " ],\n", + " remainder=\"passthrough\"\n", + ")\n", + "df_dil_encoded = preprocessor.fit_transform(df_dil)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "### نسوي سكيلنق\n", + "scaler = StandardScaler()\n", + "### نسوي لها فيت\n", + "df_dil_scaled = scaler.fit_transform(df_dil_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "plt.hist(df_dil[\"Delivery_Time\"])\n", + "plt.xlabel(\"Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Target Distribution Check\")\n", + "plt.show()\n", + "###بناءً على البلوت فا لا يوجد امبلس داتا" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_dil_scaled\n", + "y = df_dil[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "###K-fold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "## لووب عشان ك فولد\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train, X_test = X[train_idx], X[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " ### الموديل\n", + " model = RandomForestRegressor(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", + "# متوسطMAE\n", + "print(\"Average MAE across folds:\", np.mean(mae_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "impor = model.feature_importances_\n", + "plt.bar(range(len(impor)), impor)\n", + "plt.xlabel(\"Features\")\n", + "plt.title(\"Plot feature importance from trained model\")\n", + "plt.show() ### نلاحظ بان الفيتشر رقم 14 هي اهم شي بناء على الموديل" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "y_pred = model.predict(X)\n", + "plt.hist(y_pred)\n", + "plt.xlabel(\"^yDelivery Time\")\n", + "plt.title(\"Plot predicted delivery time histogram\")\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/353/Q2.ipynb b/submissions_extracted/353/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cbf44e0143b0a690bdf6b6fcbe16c45bee740c1f --- /dev/null +++ b/submissions_extracted/353/Q2.ipynb @@ -0,0 +1,348 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\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", + "### نحول الداتا\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "####بعد ما حولناها نسوي لها فايربول للتدريب\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders Create DataLoaders:\n", + "#### الان نسوي الداتا لودر\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# نطبع شكل أول باتش\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"batch shape: {X_batch.shape}\")\n", + "print(f\"batch shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "fig, axes = plt.subplots(1, 7)\n", + "for i in range(7):\n", + " axes[i].imshow(X_batch[i].permute(1, 2, 0))\n", + " axes[i].axis(\"off\")\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", + " # 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", + " # Thered 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", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\n", + " x = self.relu(self.layer1(x))\n", + " x = self.relu(self.layer2(x))\n", + " x = self.relu(self.layer3(x))\n", + " x = self.layer4(x)\n", + " return x\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).view(-1, 1)\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", + "\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).view(-1, 1)\n", + "\n", + " # Forward\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss / len(test_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train_tensor.reshape(X_train_tensor.size(0), -1).shape[1]\n", + "hidden_dim = 256\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "lr = 0.001\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = optim.Adam(model.parameters(), lr=lr)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.plot(train_losses, label=\"Training Loss\")\n", + "plt.plot(val_losses, label=\"Validation Loss\")\n", + "plt.xlabel(\"Epochs\")\n", + "plt.ylabel(\"Loss\")\n", + "plt.title(\"Plot the training and validation loss over epochs\")\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "\n", + "#### نطلع كم توقع من الداتا\n", + "model.eval()\n", + "X_batch, y_batch = next(iter(test_loader))\n", + "\n", + "with torch.no_grad():\n", + " preds = model(X_batch.view(X_batch.size(0), -1).to(device)).cpu().numpy()\n", + "\n", + "#### نعرض كم صورة مع العمر الحقيقي والمتوقع\n", + "fig, axes = plt.subplots(1, 5, figsize=(12, 3))\n", + "\n", + "for i in range(5):\n", + " axes[i].imshow(X_batch[i].permute(1, 2, 0))\n", + " axes[i].set_title(f\"Pred: {preds[i][0]:.1f}\\nTrue: {y_batch[i].item()}\")\n", + " axes[i].axis(\"off\")\n", + "\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/353/Q3.ipynb b/submissions_extracted/353/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a0e00111b06ed38c9d6b16caae568d34e07f151f --- /dev/null +++ b/submissions_extracted/353/Q3.ipynb @@ -0,0 +1,226 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dil_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(dil_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.fillna(df.median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dup=df.duplicated().sum()\n", + "df = df.drop_duplicates()\n", + "print(dup)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = pd.get_dummies(df, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "target_col = \"target\" if \"target\" in df.columns else \"Target\"\n", + "plt.hist(df[target_col])\n", + "plt.xlabel(\"Target (0 = No Default, 1 = Default)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Target Distribution Check\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "\n", + "\n", + "for train_idx, test_idx in skf.split(X, y):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "\n", + " model = CatBoostClassifier(\n", + " iterations=200,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " verbose=False\n", + " )\n", + " model.fit(X_train, y_train)\n", + "\n", + "\n", + " y_pred = model.predict(X_test)\n", + " f1 = f1_score(y_test, y_pred)\n", + " f1_scores.append(f1)\n", + "\n", + "\n", + "print(\"Average F1 across folds:\", np.mean(f1_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "impor = model.feature_importances_\n", + "plt.bar(range(len(impor)), impor)\n", + "plt.xlabel(\"Features\")\n", + "plt.title(\"Plot feature importance from trained model\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred = model.predict(X)\n", + "plt.hist(y_pred)\n", + "plt.xlabel(\"^yDelivery Time\")\n", + "plt.title(\"Plot predicted delivery time histogram\")\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/354/Q1.ipynb b/submissions_extracted/354/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab42ee1e356717ef9c45a56d170c475bfad55a52 --- /dev/null +++ b/submissions_extracted/354/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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "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)\n", + "df.head()\n", + "#here i have imported the" + ], + "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", + "print(\"Target Distribution:\")\n", + "print(df['Delivery_Time'].value_counts(normalize=True))\n", + "sns.countplot(x=df['Delivery_Time'])\n", + "plt.title(\"Target Distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "df = df.drop([\"Order_ID\"] , axis = 1)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isna().sum()\n", + "df = df.dropna()\n", + "# number is not so much so i droped it\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df.drop('Delivery_Time' , axis = 1)\n", + "y = df.Delivery_Time\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categorical_cols = X.select_dtypes(include=['object']).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " ohe = OneHotEncoder(sparse_output=False)\n", + " # TODO: Apply fit_transform to encode the column\n", + " X = X.join(\n", + " pd.DataFrame(\n", + " ohe.fit_transform(X[[col]]),\n", + " columns=ohe.get_feature_names_out([col]),\n", + " index= X.index\n", + " )\n", + " ).drop(columns=[col]) # \n", + "\n", + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "# first remove the target\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# we does not need this it is regression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# I have splitted above becouse i dont want to scale the target column\n", + "#y does not need to be scaled so i have done it before\n", + "X_scaled.shape\n", + "y.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import KFold\n", + "n_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", + "\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", + " from sklearn.ensemble import RandomForestRegressor\n", + " from sklearn.metrics import mean_absolute_error\n", + " model = RandomForestRegressor()\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test , y_pred)\n", + " print(mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.plot()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/354/Q2.ipynb b/submissions_extracted/354/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..edd7d5a9c699dbb7f3320f7c8fe0efaee3a1221e --- /dev/null +++ b/submissions_extracted/354/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "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", + "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,2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "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, hidden_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.layer4 = nn.Linear(hidden_dim , output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.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 = 3*36*36 # MNIST images flattened\n", + "hidden_dim = 5 # Design choice\n", + "output_dim = 1 # 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", + "# Run Training\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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "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}')\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/354/Q3.ipynb b/submissions_extracted/354/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4426c15d24372ce97e34e5125cb3b0e519ac6536 --- /dev/null +++ b/submissions_extracted/354/Q3.ipynb @@ -0,0 +1,217 @@ +{ + "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", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "#i have imported pandas and os to deal with the files then read it as csv file" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n", + "# this method print the head of the first lines" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n", + "# info is function that print information about the data agout columns and rows" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n", + "#describe method is useful method to know the mean and median and some statistical info" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "num_cols = df.select_dtypes(exclude =[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " df[col] = df[col].fillna(df.mode[0])\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df.mean)" + ], + "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", + "\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", + "label_encoders" + ], + "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", + "print(\"Target Distribution:\")\n", + "print(df.value_counts(normalize=True))\n", + "sns.countplot(x=df['Target'])\n", + "plt.title(\"Target 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 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", + "X = df.drop(['Target'] , axis = 1)\n", + "y = df.Target\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", + "from catboost import CatBoostClassifier\n", + "model = CatBoostClassifier() # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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/355/Q1.ipynb b/submissions_extracted/355/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..651a37666b6b3fb1d9c671dec06a00ab1c5c0d5b --- /dev/null +++ b/submissions_extracted/355/Q1.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import os" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "Q1_data = os.path.join(path, 'Q1_data.csv')\n", + "df_q1 = pd.read_csv(Q1_data)\n", + "\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", + "# Check data types and structure\n", + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "\n", + "df_q1.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_q1['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", + "# Why droping the Order_ID because this column is not relative to or data or the target value\n", + "df_q1 = df_q1.drop(columns=['Order_ID'])\n", + "df_q1.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_q1.isnull().sum() / len(df_q1)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill the numaric values\n", + "df_q1['Delivery_Time'] = df_q1['Delivery_Time'].fillna(df_q1['Delivery_Time'].mean())\n", + "df_q1['Courier_Experience_yrs'] = df_q1['Courier_Experience_yrs'].fillna(df_q1['Courier_Experience_yrs'].mean())\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Cheking the Delivery_Time and Courier_Experience_yrs\n", + "\n", + "if df_q1['Delivery_Time'].isnull or df_q1['Courier_Experience_yrs'].isnull:\n", + " print(\"There is no missing data in Delivery_Time or Courier_Experience_yrs\")\n", + " print(df_q1['Delivery_Time'].isnull().sum())\n", + " print(df_q1['Courier_Experience_yrs'].isnull().sum())\n", + "else:\n", + " print(\"There is missing data in Delivery_Time or Courier_Experience_yrs\")\n", + " print(df_q1['Delivery_Time'].isnull().sum())\n", + " print(df_q1['Courier_Experience_yrs'].isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill the object values\n", + "df_q1['Time_of_Day'] = df_q1['Time_of_Day'].fillna(df_q1['Time_of_Day'].mode()[0])\n", + "df_q1['Traffic_Level'] = df_q1['Traffic_Level'].fillna(df_q1['Traffic_Level'].mode()[0])\n", + "df_q1['Weather'] = df_q1['Weather'].fillna(df_q1['Weather'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "if df_q1['Time_of_Day'].isnull or df_q1['Traffic_Level'].isnull or df_q1['Weather'].isnull :\n", + " print(\"There is missing data in Traffic_Level, Weather or Time_of_Day\")\n", + " print(df_q1['Time_of_Day'].isnull().sum())\n", + " print(df_q1['Traffic_Level'].isnull().sum())\n", + " print(df_q1['Weather'].isnull().sum())\n", + "\n", + "else:\n", + " print(\"There is missing data in Traffic_Level, Weather or Time_of_Day\")\n", + " print(df_q1['Time_of_Day'].isnull().sum())\n", + " print(df_q1['Traffic_Level'].isnull().sum())\n", + " print(df_q1['Weather'].isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check if there is a duplicates\n", + "duplicates = df_q1.duplicated().sum()\n", + "if duplicates > 0:\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_q1.drop_duplicates(inplace=True) #Important\n", + " duplicates = df_q1.duplicated().sum()\n", + " print(f\"Duplicates Dropped and the duplicates now is {duplicates}\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "emdoced_q1 = df_q1.copy()\n", + "emdoced_q1" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = df_q1.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " emdoced_q1[col] = le.fit_transform(emdoced_q1[col]) # \n", + "emdoced_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "emdoced_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "scaler = StandardScaler()\n", + "cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t]\n", + "X = emdoced_q1[cols]\n", + "\n", + "print(X)\n", + "y = emdoced_q1[\"Delivery_Time\"]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "Scaled_X_train = scaler.fit_transform(X_train)\n", + "Scaled_X_test = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# There is no imbalance in target value becuse its regression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# i already did it in previouse cell" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(Scaled_X_test, 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/355/Q2.ipynb b/submissions_extracted/355/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4faed36034fc02689921392200674ff665192a2c --- /dev/null +++ b/submissions_extracted/355/Q2.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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, root_mean_squared_error" + ], + "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", + "\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train) # \n", + "test_dataset = TensorDataset(X_test, y_test) # \n", + "\n", + "# TODO: Create DataLoaders with batch_size=32\n", + "# [HINT]: shuffle=True for training, shuffle=False for testing\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # \n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # \n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim,out):\n", + " super(NN4Layer, self).__init__()\n", + " # TODO: Define the first linear layer: input_dim -> hidden_dim\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim) # \n", + "\n", + " # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim) # \n", + "\n", + " # TODO: Define the output layer: hidden_dim -> 1 (single value for regression)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim) # \n", + " self.layer4 = nn.Linear(hidden_dim, out) # \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", + " a3 = self.relu(self.layer2(a2)) # \n", + " # TODO: Output layer (no activation for regression)\n", + " output = self.layer4(a3) # \n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # TODO: Set the model to training mode\n", + " model.train()\n", + "\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.view(-1,1).to(device) # \n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # \n", + "\n", + " # print(outputs.shape)\n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch) # \n", + "\n", + " # TODO: Backward pass & optimization\n", + " # Step 1: Clear previous gradients\n", + " optimizer.zero_grad()\n", + "\n", + " # Step 2: Compute gradients (backward pass)\n", + " loss.backward()\n", + "\n", + " # Step 3: Update model parameters\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Calculate average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # TODO: Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # TODO: Disable gradient computation using torch.no_grad()\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # TODO: Move data to device\n", + " X_batch = X_batch.to(device) # \n", + " y_batch = y_batch.view(-1, 1).to(device) # [HINT: reshape to (-1, 1)]\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # \n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch) # \n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # \n", + "print(device)\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 32 *32 # 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", + "model = NN4Layer(input_dim, hidden_dim, 1).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.0001\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(), learning_rate) # " + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # 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": [], + "execution_count": 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/355/Q3.ipynb b/submissions_extracted/355/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a92de0af7af6c92c47eab1156a31c3f234b7da87 --- /dev/null +++ b/submissions_extracted/355/Q3.ipynb @@ -0,0 +1,167 @@ +{ + "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": [] + }, + { + "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/356/Q1.ipynb b/submissions_extracted/356/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..360975dbad370c08fa15effa2d9c751b9a3f4c55 --- /dev/null +++ b/submissions_extracted/356/Q1.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "import kagglehub\n", + "import pandas as pd\n", + "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, OneHotEncoder\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", + "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", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop([\"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", + "df = df.fillna('none')\n", + "check_missing_values(df)\n", + "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", + "import pandas as pd\n", + "\n", + "categories = pd.DataFrame({\"Animal\": ['cat', 'dog', 'cat', 'bird', 'dog']}) # DataFrame of one column\n", + "\n", + "print(\"Before encoding:\")\n", + "categories\n", + "\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', categories) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(categories[\"Animal\"]) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "import numpy as np # for random data generation\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "# Use previously generated random regression data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "model = LinearRegression() # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# Use previously generated random regression data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train Decision Tree Regressor\n", + "model = RandomForestRegressor(random_state=42) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test)\n", + "print(\"Regression Metrics\\n\" + \"-\"*30)\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train a regression model\n", + "reg_model = LinearRegression()\n", + "reg_model.fit(X_train, y_train)\n", + "y_pred = reg_model.predict(X_test)\n", + "\n", + "# Calculate metrics\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "\n", + "print(\"MSE :\", mse)\n", + "print(\"MAE :\", mae)\n", + "print(\"RMSE:\", rmse)" + ], + "execution_count": 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/356/Q2.ipynb b/submissions_extracted/356/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..721c9c8804514e951df3a32ad3ba12bdc0f1e578 --- /dev/null +++ b/submissions_extracted/356/Q2.ipynb @@ -0,0 +1,347 @@ +{ + "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 kagglehub\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", + "# 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": [], + "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", + "y_train =torch.tensor(y_train)\n", + "X_train =torch.tensor(X_train)\n", + "y_test =torch.tensor(y_test)\n", + "X_test =torch.tensor(X_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", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # \n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # \n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image = train_dataset[0]\n", + "sample_image\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", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = 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", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "learning_rate = 0.001\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "criterion = nn.CrossEntropyLoss()\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", + "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!')" + ], + "execution_count": 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/356/Q3.ipynb b/submissions_extracted/356/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..565ffe84c379ab26d387146aee9f3bdd9b052259 --- /dev/null +++ b/submissions_extracted/356/Q3.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\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", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "\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.\")\n", + "\n", + "check_missing_values(df)\n", + "df = df.fillna('none')\n", + "check_missing_values(df)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "import pandas as pd\n", + "\n", + "categories = pd.DataFrame({\"Animal\": ['cat', 'dog', 'cat', 'bird', 'dog']}) # DataFrame of one column\n", + "\n", + "print(\"Before encoding:\")\n", + "categories\n", + "\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', categories) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(categories[\"Animal\"]) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np # for random data generation\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "# Use previously generated random regression data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "model = LinearRegression() # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test)\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "\n" + ], + "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", + "# Use previously generated random regression data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train Decision Tree Regressor\n", + "model = RandomForestRegressor(random_state=42) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n", + "print(\"Regression Metrics\\n\" + \"-\"*30)\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train a regression model\n", + "reg_model = LinearRegression()\n", + "reg_model.fit(X_train, y_train)\n", + "y_pred = reg_model.predict(X_test)\n", + "\n", + "# Calculate metrics\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "\n", + "print(\"MSE :\", mse)\n", + "print(\"MAE :\", mae)\n", + "print(\"RMSE:\", rmse)" + ], + "execution_count": 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/357/Q1.ipynb b/submissions_extracted/357/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1136442b32f14df4fea64879e037f9d82891061a --- /dev/null +++ b/submissions_extracted/357/Q1.ipynb @@ -0,0 +1,389 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "# Task 1: Write your code here:\n", + "# Read the dataset `Q1_data.csv` using read_csv()\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", + "# Inspect the first few rows using head()\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Display dataset information using info()\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Show statistical description using describe()\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Plot the target distribution (delivery_time)\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Delivery_Time Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Drop the 'Order_ID' column from the data\n", + "\n", + "df2 = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df2.isnull().sum())\n", + "\n", + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day' , 'Courier_Experience_yrs' , 'Delivery_Time']\n", + "df_clean = df2.dropna(subset=stat_cols).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check and remove duplicates if any exist\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "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", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "\n", + "# categorical columns\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# output = Categorical Columns: ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "# we have Categorical Columns, so we need Encode\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "\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", + "# Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "\n", + "# All good here" + ], + "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", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['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", + "\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n", + "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 = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\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", + "feature_cols = [\"Distance_km\" ,\"Weather\" ,\"Traffic_Level\" ,\"Time_of_Day\" ,\"Vehicle_Type\",\"Preparation_Time_min\" ,\"Courier_Experience_yrs\" ]\n", + "\n", + "\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_fold_pred, bins=50, edgecolor='black')\n", + "plt.title('predicted delivery time ')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('predicted delivery time ')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install CatBoost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/357/Q2.ipynb b/submissions_extracted/357/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4652fdcb280409249c7d721f9c9574a32e9b9f53 --- /dev/null +++ b/submissions_extracted/357/Q2.ipynb @@ -0,0 +1,435 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "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", + "\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", + "\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", + "\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": [ + "# 5. Display sample images\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\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", + "\n", + " # Output layer TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\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", + "\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": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 36 * 36\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 1\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", + "\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot()\n", + "plt.plot()\n", + "plt.title('some predictions')\n", + "plt.xlabel('actual age')\n", + "plt.ylabel('predicted age')\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/357/Q3.ipynb b/submissions_extracted/357/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf68281436a0e0371736c089080a70572e02397b --- /dev/null +++ b/submissions_extracted/357/Q3.ipynb @@ -0,0 +1,314 @@ +{ + "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": [ + "# 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 values\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", + "# no need\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "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", + "#73% so there's an imbalance." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.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)" + ], + "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 catboost import CatBoostClassifier\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " 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]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = importances\n", + "print(golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/358/Q1.ipynb b/submissions_extracted/358/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cb6c1dfb9a9c1b8745c41218777a1081e804abaf --- /dev/null +++ b/submissions_extracted/358/Q1.ipynb @@ -0,0 +1,274 @@ +{ + "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 numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import train_test_split\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", + "\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Plot')\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_clean = df.drop(['Order_ID'], axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df['Weather'].mode())\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df['Time_of_Day'].mode())\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df['Traffic_Level'].mode())\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "label_encoder = LabelEncoder()\n", + "\n", + "df_clean['Weather'] = label_encoder.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = label_encoder.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Time_of_Day'] = label_encoder.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = label_encoder.fit_transform(df_clean['Vehicle_Type'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "target = 'Delivery_Time'\n", + "feature_cols = df_clean.drop(target, axis=1).columns\n", + "\n", + "# scaling\n", + "scaler = StandardScaler()\n", + "\n", + "X_scaled = scaler.fit_transform(df_clean[feature_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df_clean.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean[target]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in enumerate(skf.split(X, y), start=1):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " 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" + ], + "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", + "\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/358/Q2.ipynb b/submissions_extracted/358/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0badab3b9193c6139388d5bf9483173b8b23ff5 --- /dev/null +++ b/submissions_extracted/358/Q2.ipynb @@ -0,0 +1,378 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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": [ + "# 0. importing\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader, TensorDataset\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, Adam\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "X_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\"Age: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + "\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.layer5(a3)\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", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 64\n", + "output_dim = 100 # 0-99 years old\n", + "\n", + "model = NN4Layer(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 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.01\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "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/358/Q3.ipynb b/submissions_extracted/358/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d91598e97556f75ddeecb0c59eef24fd9a0a117e --- /dev/null +++ b/submissions_extracted/358/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 numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_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/359/Q1.ipynb b/submissions_extracted/359/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0b352f6ea7abd17f8d938d6e0aae5f3c0cca71bb --- /dev/null +++ b/submissions_extracted/359/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 lyb\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")#where path\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()#show data head" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() #Display dataset information" + ], + "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", + "#drop Order_ID\n", + "df = df.drop(['Order_ID'], axis=1)# axis=1 for cloumn\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + "print(\"-\"*10)\n", + "\n", + "#handel missing value\n", + "cols = ['Delivery_Time','Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Drop rows where targetor key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n", + "print(f\"After dropping missing : {df_clean.shape}\")\n", + "\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())#check if there any more null" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + " #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\") #not need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#split\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, 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", + "\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n", + "\n" + ], + "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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/359/Q2.ipynb b/submissions_extracted/359/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0a0bf8f5f3645802b8589d5c6add90b9a0e28ef4 --- /dev/null +++ b/submissions_extracted/359/Q2.ipynb @@ -0,0 +1,424 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "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 #Number of parallel CPU workers to load data faster\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\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\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + " # TODO: Define the first linear layer: input_dim -> hidden_dim\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: Define the second and third linear layer: hidden_dim -> hidden_dim\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: Define the output layer: hidden_dim -> 1 (single value for regression)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + "\n", + " # TODO: Define ReLU activation\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " # define how model train to produce predict\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", + " # FIX: Changed self.layer1(a1) to self.layer2(a1)\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3=self.relu(self.layer3(a2))\n", + "\n", + " # TODO: Output layer (no activation for regression)\n", + " output =self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # TODO: Set the model to evaluation mode\n", + " # Set the model to evaluation mode eval not stop gradint\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) # shape: (batch_size, num_features)\n", + " y_batch =y_batch.view(-1, 1).to(device) # shape: (batch_size,)\n", + " # TODO: Forward pass - get model predictions\n", + " outputs =model(X_batch) # \n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + " #Set up the device (use GPU if available, otherwise CPU)\n", + "device =torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + " #Model parameters\n", + "input_dim = X_train.shape[1] # Number of 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", + "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", + "#Define criterion (loss function) - use MSELoss for regression\n", + "criterion =criterion = nn.MSELoss() #\n", + "\n", + "# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n", + "optimizer = AdamW(model.parameters(), 0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "\n", + "num_epochs = 20 # Hyperparameters\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy() # Move to device, get predictions, move to CPU, convert to numpy\n", + "\n", + "# Ensure y_test is a numpy array for sklearn metrics\n", + "y_test_np = y_test.numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n", + "mae = mean_absolute_error(y_test_np, predictions) #\n", + "mse = mean_squared_error(y_test_np, predictions) #\n", + "rmse = np.sqrt(mse) # <\n", + "r2 = r2_score(y_test_np, predictions) #\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")\n", + "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/359/Q3.ipynb b/submissions_extracted/359/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f8e5d4e25a5185a609b116e9d03e6f84447ed98e --- /dev/null +++ b/submissions_extracted/359/Q3.ipynb @@ -0,0 +1,303 @@ +{ + "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)\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "# Fill missing values with mean for each column\n", + "df= df.fillna(df.mean())\n", + "print('-'*20)\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", + " #Do we have categorical columns if yes 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", + "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", + " #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\") # impalenced" + ], + "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)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q# downlawd kagglehub\n", + "\n", + "clear_output()" + ], + "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 train_test_split\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=42)\n", + "from catboost import CatBoostClassifier\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "\n", + "\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", + " # 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", + "\n", + "\n", + "# Train\n", + "model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + "y_pred = model.predict(X_test)\n", + "accuracy = accuracy_score(y_test, y_pred )\n", + "f1 = f1_score(y_test, y_pred , zero_division=0)\n", + "\n", + "print(f\"Accuracy: {accuracy/5}\")\n", + "print(f\"f1: {f1/5}\")" + ], + "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': X ,\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/36/Q1.ipynb b/submissions_extracted/36/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6e3aaf56670982c95313f2fa8d4b776f8c14d468 --- /dev/null +++ b/submissions_extracted/36/Q1.ipynb @@ -0,0 +1,206 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\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", + "path = kagglehub.dataset_download(\"austinreese/craigslist-carstrucks-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "csv_path = os.path.join(path, \"Placement_Data_Full_Class.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\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", + "food_delivery.describe()#idk" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.title('food delivery')\n", + "plt.xlabel('time')\n", + "plt.ylabel('Frequency')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['price', 'food']\n", + "df_clean = food_deliverry[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['price', 'food'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "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/360/Q1.ipynb b/submissions_extracted/360/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0f952ade75f6413b2318ad9efede620520b9da14 --- /dev/null +++ b/submissions_extracted/360/Q1.ipynb @@ -0,0 +1,366 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Load the dataset\n", + "delivery_time_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery_time = pd.read_csv(delivery_time_path)\n", + "\n", + "print(f\"Dataset shape: {df_delivery_time.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_delivery_time.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_delivery_time.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery_time.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Target Distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery_time['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('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", + "\n", + "df_delivery_time.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery_time)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pandas._libs import missing\n", + "\n", + "missing_cols = ['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time']\n", + "\n", + "df_delivery_time[missing_cols] = df_delivery_time[missing_cols].fillna('unknown')\n", + "df_delivery_time\n", + "\n", + "missing_values_check = df_delivery_time.isnull().sum()\n", + "missing_values_check" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery_time)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_delivery_time.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type','Courier_Experience_yrs','Delivery_Time']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_delivery_time[col] = le.fit_transform(df_delivery_time[col].astype(str))\n", + "\n", + "df_delivery_time.head()\n", + "\n", + "# Use One-Hot-Encoder for Bonus*******" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values remaining:\", df_delivery_time.isnull().sum().sum())\n", + "\n", + "categorical_cols = df_delivery_time.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df_delivery_time.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "df_delivery_time[features] = scaler.fit_transform(df_delivery_time[features])\n", + "\n", + "df_delivery_time.head()\n", + "# ______________________________________\n", + "\n", + "# # Define features (X) and target (y)\n", + "# feature_cols_template = ['feature1', 'feature2', 'engineered_feature'] # REPLACE WITH YOUR FEATURE COLUMNS\n", + "# target_col_template = 'Delivery_Time'\n", + "\n", + "# X = df_delivery_time[feature_cols_template]\n", + "# y = df_delivery_time[target_col_template]\n", + "\n", + "# # Split data (e.g., 80% train, 20% test)\n", + "# X_train_tpl, X_test_tpl, y_train_tpl, y_test_tpl = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# print(f\"Train set shape: {X_train_tpl.shape}\")\n", + "# print(f\"Test set shape: {X_test_tpl.shape}\")\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", + "X = df_delivery_time.drop(\"Delivery_Time\",axis=1)\n", + "y = df_delivery_time['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", + "\n", + "# Initialize K-Fold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in enumerate(kfold.split(X), start=1):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + "\n", + " # Initialize the model\n", + " # Adjust hyperparameters like n_estimators, max_depth as needed\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "\n", + "\n", + "print(\"Model trained!\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = model['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/360/Q2.ipynb b/submissions_extracted/360/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9076d82d1978df114de45cbc5653fdaf06dfb013 --- /dev/null +++ b/submissions_extracted/360/Q2.ipynb @@ -0,0 +1,480 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "from torch.optim import Adam\n", + "\n", + "\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 numpy as np\n", + "from collections import Counter" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train_t = torch.tensor(X_train)\n", + "X_test_t = torch.tensor(X_test)\n", + "y_train_t = torch.tensor(y_train)\n", + "y_test_t = torch.tensor(y_test)\n", + "\n", + "print(X_train_t.shape,\n", + "X_test_t.shape,\n", + "X_train_t.shape,\n", + "y_test_t.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data.dataset import TensorDataset\n", + "# 2. Create TensorDataset objects\n", + "\n", + "# X_train_t.dataset\n", + "train_dataset_X = TensorDataset(X_train_t)\n", + "train_dataset_y = TensorDataset(y_train_t)\n", + "test_dataset_X = TensorDataset(X_test_t)\n", + "test_dataset_y = TensorDataset(y_test_t)\n", + "\n", + "train_dataset_X.flatten(start_dim=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader_X = DataLoader( train_dataset_X, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader_X = DataLoader( test_dataset_X, batch_size=32, shuffle=False, num_workers=2)\n", + "# DataLoader for training data\n", + "train_loader_y = DataLoader( train_dataset_y , batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader_y = DataLoader( test_dataset_y, batch_size=32, shuffle=False, num_workers=2)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(train_loader_X)" + ], + "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_X))\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", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1:\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " z5 = self.layer5(a3)\n", + "\n", + "\n", + " return z5\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", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36 # images flattened (RGB)\n", + "\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "output_dim = 10\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 15\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader_X, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader_y, 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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "# Get some test images\n", + "model.eval()\n", + "\n", + "test_images, test_labels = next(iter(test_loader_X))\n", + "test_images = test_images.to(device)\n", + "\n", + "with torch.no_grad():\n", + " reconstructed = model(test_images)\n", + "\n", + "# Move to CPU for plotting\n", + "test_images = test_images.cpu()\n", + "reconstructed = reconstructed.cpu()\n", + "\n", + "# Plot original vs reconstructed\n", + "n_images = 9\n", + "fig, axes = plt.subplots(2, n_images, figsize=(18, 6))\n", + "\n", + "for i in range(n_images):\n", + " # Original\n", + " axes[0, i].imshow(test_images[i].squeeze(), cmap='gray')\n", + " axes[0, i].axis('off')\n", + " axes[0, i].set_title(f'Original - \"{test_labels[i]}\"', fontsize=12)\n", + "\n", + " # Reconstructed\n", + " axes[1, i].imshow(reconstructed[i].squeeze(), cmap='gray')\n", + " axes[1, i].axis('off')\n", + " axes[1, i].set_title(f'Reconstructed - \"{test_labels[i]}\"', fontsize=12)\n", + "\n", + "plt.suptitle('Original vs Reconstructed Images', fontsize=14)\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "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/360/Q3.ipynb b/submissions_extracted/360/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6f8e1f0df498775ca8962b9a66e983410fa28a3b --- /dev/null +++ b/submissions_extracted/360/Q3.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "golden_feature_path = os.path.join(path, 'Q3_data.csv')\n", + "df_golden_f = pd.read_csv(golden_feature_path)\n", + "\n", + "print(f\"Dataset shape: {df_golden_f.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_golden_f.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_golden_f.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_golden_f.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_golden_f)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pandas._libs import missing\n", + "# TODO: Fill missing type2\n", + "# missing_cols = ['P_2','B_2','S_3','D_41','B_3','D_141','D_142','D_143','D_144','D_145']\n", + "\n", + "df_golden_f = df_golden_f.fillna('unknown').columns\n", + "df_golden_f\n", + "\n", + "missing_values_check = df_golden_f.isnull().sum()\n", + "missing_values_check\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values remaining:\", df_golden_f.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_golden_f)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#There is no categorical data.\n", + "df_golden_f.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "features = df_golden_f.columns.drop(\"Target\")\n", + "\n", + "# # Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "df_golden_f[features] = scaler.fit_transform(df_golden_f[features])\n", + "\n", + "df_golden_f.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Target Distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_golden_f['Target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_golden_f.drop(\"Target\",axis=1)\n", + "y = df_golden_f['Target']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "# Initialize K-Fold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in enumerate(kfold.split(X), start=1):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + "\n", + " # Initialize the model\n", + " # Adjust hyperparameters like n_estimators, max_depth as needed\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "\n", + "\n", + "print(\"Model trained!\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/361/Q1.ipynb b/submissions_extracted/361/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4ae3ac3824db1c471ad94a009842b972f7ad622f --- /dev/null +++ b/submissions_extracted/361/Q1.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset downloaded to: {path}\")\n", + "print(f\"CSV file loaded from: {food_path}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 rows of the DataFrame:\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"DataFrame Info:\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nDataFrame Description:\")\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"Delivery_Time: {df['Delivery_Time'].sum()}\")\n", + "print(f\"normal: {(df['Delivery_Time'] == 0).sum()}\")" + ], + "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", + "print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\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 6: 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 1: Write your code here:\n", + "#Split features from target\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "# 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)" + ], + "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/361/Q2.ipynb b/submissions_extracted/361/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a4af0a07dca8513b3d4db836f7b1e1686c75c7eb --- /dev/null +++ b/submissions_extracted/361/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", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from torch.optim import AdamW\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "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": [ + "# 5. Display sample images\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # 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", + "#Set up the device\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Hyperparameters\n", + "num_epochs = 25\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\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", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/361/Q3.ipynb b/submissions_extracted/361/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a4fe77f409b7ae75bb2fbf67a9a078eab452ca20 --- /dev/null +++ b/submissions_extracted/361/Q3.ipynb @@ -0,0 +1,234 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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 = pd.read_csv(g_path)\n", + "\n", + "print(f\"Dataset downloaded to: {path}\")\n", + "print(f\"CSV file loaded from: {g_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", + "# Do we have duplicate \"rows\"\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n", + "\n", + "# Do we have duplicate \"samples\"\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = MinMaxScaler()\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 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\",axis=1)\n", + "y = df['Target']\n", + "\n", + "# 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)" + ], + "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: 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/362/Q1.ipynb b/submissions_extracted/362/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..304e8ecffc14aef6f946eed139dacc6c5f9b2e37 --- /dev/null +++ b/submissions_extracted/362/Q1.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "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.title('Delivery time Distribution')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_q1.drop(columns=['Order_ID']).copy()\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# # fill Courier_Experience_yrs missing value with mode\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].median())\n", + "\n", + "# # fill Delivery_Time missing value with mode\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].median())\n", + "\n", + "# Check if there any missing values\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder #import OneHotEncoder\n", + "# ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling\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 = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', '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", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data) قيم مستمرة\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", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(data_standard_scaled, y)\n", + "print(\"Model trained!\")\n", + "# Predict and evaluate\n", + "y_pred = model.predict(data_standard_scaled)\n", + "\n", + "mae = mean_absolute_error(y, 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", + "import matplotlib.pyplot as plt\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/362/Q2.ipynb b/submissions_extracted/362/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..96271a1b81eefb5488f35cacf30667af4f54b306 --- /dev/null +++ b/submissions_extracted/362/Q2.ipynb @@ -0,0 +1,375 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "# import torch\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", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\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", + "# Plotting results\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + "\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, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.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", + "\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + "\n", + " X_batch = X_batch.to(device)\n", + "\n", + "\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + "\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + "\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", + "\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", + "\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", + " 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", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = X_train.shape[1]\n", + "\n", + "\n", + "hidden_dim = 14\n", + "\n", + "\n", + "output_dim = 4\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "\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", + "# Run Training\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "\n", + "for epoch in range(num_epochs):\n", + "\n", + "\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + "\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\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", + "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/362/Q3.ipynb b/submissions_extracted/362/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..122dda54a85cb44bba3f342d0f81dc6dbeb9f564 --- /dev/null +++ b/submissions_extracted/362/Q3.ipynb @@ -0,0 +1,167 @@ +{ + "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:" + ], + "execution_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/363/Q1.ipynb b/submissions_extracted/363/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f68d0b7071d1ff58ab050e6a3c6ca9dea565bbb6 --- /dev/null +++ b/submissions_extracted/363/Q1.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/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", + "# 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(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='yellow')\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", + "features = df.columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:###########################\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df= df[cols].copy()\n", + "for col in cols:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: ###########\n", + "from sklearn.preprocessing import LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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": [ + "# Task 1: Write your code here:\n", + "# Define features and target\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": [ + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from tqdm import tqdm\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\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", + "\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", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#task 2\n", + "# Stratified split\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\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\"in train: {y_train.sum()}, in test: {y_test.sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#task 3\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/363/Q2.ipynb b/submissions_extracted/363/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b9e7ffba1db73b46c77593b25f5c3e346723319 --- /dev/null +++ b/submissions_extracted/363/Q2.ipynb @@ -0,0 +1,374 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "# 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", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\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": [ + "# Run Training\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\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/364/Q1.ipynb b/submissions_extracted/364/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3212384bf59d42b30134a19d4257944ed54f473a --- /dev/null +++ b/submissions_extracted/364/Q1.ipynb @@ -0,0 +1,270 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\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", + "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", + "# Analyze missing values\n", + "missing_percentage = (df_delivery.isnull().sum() / len(df_delivery)) * 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", + "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", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Predict Food 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", + "# 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", + "# Fill missing type2\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode type columns\n", + "le = LabelEncoder()\n", + "df_clean['type1'] = le.fit_transform(df_clean['type1'])\n", + "df_clean['type2'] = le.fit_transform(df_clean['type2'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Define features and target\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", + "\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\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", + "# 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", + "# 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", + "# 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", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Predict Food 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/364/Q2.ipynb b/submissions_extracted/364/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a4e78e5650e33eecf0372cf172cc75a8612f65b9 --- /dev/null +++ b/submissions_extracted/364/Q2.ipynb @@ -0,0 +1,336 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Create tensors\n", + "import torch\n", + "x = torch.tensor([0.0, 3.0, 1.0, 2.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# 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", + "# 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", + "lass 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(a4) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# 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", + "num_epochs = 20\n", + "learning_rate = 0.001\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/364/Q3.ipynb b/submissions_extracted/364/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e12f2a867ee3c206ef9b01fd40289a9698d42ef8 --- /dev/null +++ b/submissions_extracted/364/Q3.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "\n", + "\n", + "\n", + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "Q3_data = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(Q3_data)\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", + "# Analyze missing values\n", + "missing_percentage = (df_cars.isnull().sum() / len(df_cars)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 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", + "# 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": [ + "# 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, \"status\")" + ], + "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_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", + "# 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", + "# 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", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\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/365/Q1.ipynb b/submissions_extracted/365/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2c3412b3ab8c1d3eec8174ee38b7cea77eafddd6 --- /dev/null +++ b/submissions_extracted/365/Q1.ipynb @@ -0,0 +1,438 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Data_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('target distribution (delivery_time)')\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.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Handle missing values appropriately\n", + " #(Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "missing_values = df.isnull().sum()\n", + "print(missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "\n", + "df_clean = df_clean.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs', 'Delivery_Time'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "print('data before encoding:\\n', df_clean)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df_clean)\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "data_scaled = scaler.fit_transform(df_clean)" + ], + "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", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier as RandomForest" + ], + "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", + "\n", + "model = RandomForest()\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):\n", + " X_fold_train, X_fold_val = X[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", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': y,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")\n", + "\n", + "plt.grid(True)\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.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", + "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 Bonus: Write your code here:\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold as skf\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 & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/365/Q2.ipynb b/submissions_extracted/365/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c16650c72262f3a26810815877b45f92bdc3a9d4 --- /dev/null +++ b/submissions_extracted/365/Q2.ipynb @@ -0,0 +1,368 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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.utils.data import 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": [ + "# 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", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)" + ], + "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\"Label: {sample_label}\")\n", + "print(f\"\\n Image shape: {sample_image.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(8, 4))\n", + "plt.subplot(2, 3, 1 + 1)\n", + "plt.imshow(images[1].squeeze(), cmap='gray')\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, hidden_dim2, 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.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a1)\n", + " a3 = self.relu(z2)\n", + "\n", + " output = self.layer3(a2)\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 28 * 28\n", + "hidden_dim = 14\n", + "hidden_dim2 = 14\n", + "output_dim = 10\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim , hidden_dim2, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "# 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", + "\n", + "model.eval()\n", + "images, labels = next(iter(test_loader))\n", + "\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/365/Q3.ipynb b/submissions_extracted/365/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..de85a010a3eaa54fca35f0a6ee26fb39148ef85e --- /dev/null +++ b/submissions_extracted/365/Q3.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, 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", + "Data_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df = pd.read_csv(Data_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": [ + "categorical_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "categorical_cols = list(categorical_cols)\n", + "print(\"Categorical:\", categorical_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\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": [ + "df_clean = df[categorical_cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "\n", + "df_clean = df_clean.dropna(subset=['Target'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n", + "\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", + "\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", + "scaler = StandardScaler()\n", + "data_scaled = scaler.fit_transform(df[df_clean])" + ], + "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", + "X = df_clean[categorical_cols]\n", + "y = df_clean['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "model = CatBoostClassifier\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):\n", + " X_fold_train, X_fold_val = X[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': 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", + "golden_feature = \"target\"\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['odometer'].dropna(), bins=50, edgecolor='black', color='green')\n", + "plt.title('the golden feature')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: 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()\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": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/366/Q1.ipynb b/submissions_extracted/366/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c70ee2773099717d5c47387c4b01fb29b63dacb7 --- /dev/null +++ b/submissions_extracted/366/Q1.ipynb @@ -0,0 +1,350 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\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", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "data = pd.read_csv(food_path)\n", + "data" + ], + "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() # I see that there is a Missing Values in mulit columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe() #need the Scale\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5)) #from the plot I see that the target distribution is in normal distribution but there is some outliers\n", + "plt.hist(data['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", + "data = data.drop(columns=['Order_ID'], axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data # Order_ID droped" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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(data) # there is a mising values in the target col!!\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Handle missing values\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Handle missing values\n", + "#for Categorical col\n", + "Categorical= data.select_dtypes(include=[\"object\"]).columns\n", + "for col in list(Categorical):\n", + " data[col]= data[col].fillna(data[col].mode()[0])\n", + "\n", + "\n", + "#for col Courier_Experience_yrs fil it with the mean becaues there is not outliers\n", + "data['Courier_Experience_yrs']=data['Courier_Experience_yrs'].fillna(data['Courier_Experience_yrs'].mean())\n", + "\n", + "#for col Delivery_Time fil it with the median becaues there is outliers\n", + "data['Delivery_Time']=data['Delivery_Time'].fillna(data['Delivery_Time'].median())\n", + "\n", + "#last cheack\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(data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Task 4: Write your code here:\n", + "#Encode categorical variables\n", + "#note: this may lead to data leakage so we must Split FIRST (avoid leakage)\n", + "\n", + "label_encoder = LabelEncoder()\n", + "for col in Categorical:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col].astype(str))\n", + "data\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#feature scaling\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data) # Apply fit_transform\n", + "\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Delivery_Time 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", + "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", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "\n", + "X = data.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = data[\"Delivery_Time\"].astype(float)\n", + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "n_splits = 5 # K\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", + " # 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 the model\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "print(\"MAE :\", mae)\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': X,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/366/Q2.ipynb b/submissions_extracted/366/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9cbd129bacede2008b5fb362c5ef2d7cbdf61548 --- /dev/null +++ b/submissions_extracted/366/Q2.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub # for importing the dataset\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 TensorDataset,DataLoader\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()}\") # checking for GPU" + ], + "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.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", + "# Training dataset\n", + "train_dataset = Image(root='./datasets', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = Image(root='./datasets', train=False, transform=to_tensor, download=True)\n", + "\n", + "# Print one sample from the dataset\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class 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 of previous and output layer? (hint: hidden neurons? num of classes?)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " # Output layer TODO\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", + "\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 * 36* 36\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN5Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/366/Q3.ipynb b/submissions_extracted/366/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..77355a8067b31700423c3eceb19b8ce96aa0a65d --- /dev/null +++ b/submissions_extracted/366/Q3.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\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", + "golden_path = os.path.join(path, 'Q3_data.csv')\n", + "data = pd.read_csv(golden_path)\n", + "data" + ], + "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", + "# Task 2: 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(data) # there is a mising values in the target col!!\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data = data.drop(columns=['Order_ID'], axis=1)" + ], + "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:\n", + " # Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/367/Q1.ipynb b/submissions_extracted/367/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a93ebd946cfc2551586c41a5e5af90c4fbc1e2b8 --- /dev/null +++ b/submissions_extracted/367/Q1.ipynb @@ -0,0 +1,331 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " # task 5\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Minutes')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "df_food.drop(\"Order_ID\", axis=1, inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in ['Traffic_Level', 'Traffic_Level', 'Weather', 'Time_of_Day']:\n", + " df_food[col] = df_food[col].fillna(df_food[col].mode()[0])\n", + "\n", + "df_food['Courier_Experience_yrs'] = df_food['Courier_Experience_yrs'].fillna(df_food['Courier_Experience_yrs'].mean())\n", + "df_food['Delivery_Time'] = df_food['Delivery_Time'].fillna(df_food['Delivery_Time'].mean())\n", + "\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", + "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": [ + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food[col] = le.fit_transform(df_food[col].astype(str))\n", + "\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df_food.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df_food[numerical_cols] = scaler.fit_transform(df_food[numerical_cols])\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Minutes')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.shape\n", + "df_food.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "X = df_food.drop(\"Delivery_Time\", axis=1)\n", + "y = df_food['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, shuffle=True,)\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\"\"\"\n", + "for train_idx, val_idx in kfold.split(X,y):\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", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "for fold_idx, (train_index, test_index) in enumerate(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.fit(X_train, y_train)\n", + " y_fold_pred = model.predict(X_test)\n", + "\n", + " mae_scores.append(mean_absolute_error(y_test, 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.sum():,.2f}\")\n", + "print(f\"Avg of MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols=[\"Traffic_Level\",'Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Weather','Distance_km']\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, 6))\n", + "plt.hist(y_fold_pred,)\n", + "plt.title('Feature predicted time')\n", + "plt.xlabel('minutes')\n", + "plt.gca()\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/367/Q2.ipynb b/submissions_extracted/367/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f6a70e9689eaec06097d9eaefecdb8363d1328a8 --- /dev/null +++ b/submissions_extracted/367/Q2.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "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", + "# 4. Print shape of one batch\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", + "images, labels = next(iter(train_loader))\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].permute(1, 2, 0), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " 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", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + " outputs = model(X_batch)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + " 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", + "input_dim = 3*36*36\n", + "hidden_dim = 64\n", + "model = NN4Layer(input_dim,hidden_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = Adam(model.parameters() ,learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies=[]\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss,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:.4f}')\n", + "\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:\n", + "model.eval()\n", + "with torch.no_grad():\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "plt.figure(figsize=(8, 6))\n", + "plt.scatter(y_test.numpy(), predictions.flatten(),\n", + "lpha=0.5, s=10, c='steelblue')\n", + "\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual age', fontsize=12)\n", + "plt.ylabel('Predicted age', fontsize=12)\n", + "plt.title('Predicted vs Actual age', 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/367/Q3.ipynb b/submissions_extracted/367/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..61cc568811af79eff9687ce104d5cf944649da81 --- /dev/null +++ b/submissions_extracted/367/Q3.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df.select_dtypes(include=[\"int64\",\"float64\"]).columns.drop(\"Target\")\n", + "for col in numerical_cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "# no need to encoding" + ], + "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\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df['Target']\n", + "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, shuffle=True,)\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " 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", + " f1 = f1_score(y_test, y_pred, zero_division=0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\" F1-Score: {f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols=df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\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=(20, 10))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "model.feature_importances_>10 # note that the first is only true" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols # here the first is" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# so the Golden Feature is ( P_2 )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Golden_Feature= feature_importance.filter(model.feature_importances_>10)\n", + "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/368/Q1.ipynb b/submissions_extracted/368/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..261f95f0ee3654d2f655f3e765162b705ba4b247 --- /dev/null +++ b/submissions_extracted/368/Q1.ipynb @@ -0,0 +1,347 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#imports" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# --- System & Utilities ---\n", + "import os\n", + "import warnings\n", + "from IPython.display import clear_output\n", + "from tqdm import tqdm\n", + "import kagglehub\n", + "\n", + "# --- Data Manipulation & Visualization ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Magic command for plotting\n", + "%matplotlib inline\n", + "# Filter warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# --- Machine Learning: Scikit-Learn ---\n", + "# Datasets\n", + "from sklearn.datasets import load_breast_cancer\n", + "\n", + "# Preprocessing\n", + "from sklearn.preprocessing import (\n", + " StandardScaler,\n", + " LabelEncoder,\n", + " OneHotEncoder,\n", + " MinMaxScaler\n", + ")\n", + "\n", + "# Model Selection\n", + "from sklearn.model_selection import (\n", + " train_test_split,\n", + " StratifiedKFold,\n", + " KFold,\n", + " cross_val_score\n", + ")\n", + "\n", + "# Metrics\n", + "from sklearn.metrics import (\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix, ConfusionMatrixDisplay,\n", + " mean_squared_error, mean_absolute_error, r2_score,\n", + " mean_squared_error as mse, mean_absolute_error as mae # Aliases used in notebook\n", + ")\n", + "\n", + "# Models: Linear & SVM\n", + "from sklearn.linear_model import (\n", + " LinearRegression,\n", + " LogisticRegression,\n", + " Ridge,\n", + " Lasso\n", + ")\n", + "from sklearn.svm import SVC, SVR\n", + "\n", + "# Models: Neighbors & Trees\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n", + "\n", + "# Models: Ensemble\n", + "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n", + "\n", + "# --- Machine Learning: Boosting Libraries ---\n", + "from xgboost import XGBClassifier\n", + "from lightgbm import LGBMRegressor\n", + "from catboost import CatBoostClassifier, CatBoostRegressor\n", + "\n", + "# --- Deep Learning: PyTorch ---\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# --- Computer Vision: TorchVision ---\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 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", + "df_noid=df.drop('Order_ID',axis=1).copy()\n", + "df_noid.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_noid.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", + "cols=[\"Weather\",\"Traffic_Level\",\"Time_of_Day\"]\n", + "for miss in cols:\n", + " df_noid[miss] = df_noid[miss].fillna(\"unknown\")\n", + "for miss in ['Delivery_Time',\"Courier_Experience_yrs\"]:\n", + " df_noid[miss] = df_noid[miss].fillna(df_noid[miss].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_noid.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_noid.info()\n", + "cat_col = [\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\"]\n", + "for col in cat_col:\n", + " le = LabelEncoder()\n", + " df_noid[col] = le.fit_transform(df_noid[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "scaler = StandardScaler()\n", + "df_scale = scaler.fit_transform(df_noid.drop(columns=[\"Delivery_Time\"]).copy())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here\n", + "df_noid.describe()\n", + "#1106 and 8 so there is imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#i dont know how to split after scaleing but i will do it like this\n", + "# Define features (X) and target (y)\n", + "print(df_noid)\n", + "X = df_noid.drop(columns=[\"Delivery_Time\"]).copy()\n", + "y = df_noid[\"Delivery_Time\"]\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "# StratifiedKFold can be used in both regrssion and classfcation but i will use kfold\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1): # \"start\" for fold try changeing it ( not important) \"enuyumrate \" for indexing a vlue\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]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot for Decision Tree Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)],\n", + " [min(y_test), max(y_test)],\n", + " 'r--', linewidth=2)\n", + "\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Decision Tree)\")\n", + "plt.title(\"Decision Tree Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/368/Q2.ipynb b/submissions_extracted/368/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df6620841a326e9927ea1b0b004df2bc7901b1b1 --- /dev/null +++ b/submissions_extracted/368/Q2.ipynb @@ -0,0 +1,461 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# --- System & Utilities ---\n", + "import os\n", + "import warnings\n", + "from IPython.display import clear_output\n", + "from tqdm import tqdm\n", + "import kagglehub\n", + "\n", + "# --- Data Manipulation & Visualization ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Magic command for plotting\n", + "%matplotlib inline\n", + "# Filter warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# --- Machine Learning: Scikit-Learn ---\n", + "# Datasets\n", + "from sklearn.datasets import load_breast_cancer\n", + "\n", + "# Preprocessing\n", + "from sklearn.preprocessing import (\n", + " StandardScaler,\n", + " LabelEncoder,\n", + " OneHotEncoder,\n", + " MinMaxScaler\n", + ")\n", + "\n", + "# Model Selection\n", + "from sklearn.model_selection import (\n", + " train_test_split,\n", + " StratifiedKFold,\n", + " KFold,\n", + " cross_val_score\n", + ")\n", + "\n", + "# Metrics\n", + "from sklearn.metrics import (\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix, ConfusionMatrixDisplay,\n", + " mean_squared_error, mean_absolute_error, r2_score,\n", + " mean_squared_error as mse, mean_absolute_error as mae # Aliases used in notebook\n", + ")\n", + "\n", + "# Models: Linear & SVM\n", + "from sklearn.linear_model import (\n", + " LinearRegression,\n", + " LogisticRegression,\n", + " Ridge,\n", + " Lasso\n", + ")\n", + "from sklearn.svm import SVC, SVR\n", + "\n", + "# Models: Neighbors & Trees\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n", + "\n", + "# Models: Ensemble\n", + "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n", + "\n", + "# --- Machine Learning: Boosting Libraries ---\n", + "from xgboost import XGBClassifier\n", + "from lightgbm import LGBMRegressor\n", + "from catboost import CatBoostClassifier, CatBoostRegressor\n", + "\n", + "# --- Deep Learning: PyTorch ---\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# --- Computer Vision: TorchVision ---\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)#if regrssion float 32 if classfcation long\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", + "# TODO: Create TensorDatasets for training and testing\n", + "# [HINT]: Use TensorDataset(features, labels)\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test) # \n", + "\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# TODO: Create DataLoaders with batch_size=32\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\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", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim,output_dim=1):\n", + " super(NN4Layer, self).__init__()\n", + " # TODO: Define the first linear layer: input_dim -> hidden_dim\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim) # \n", + "\n", + " # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim) # \n", + "\n", + " # TODO: Define the output layer: hidden_dim -> 1 #important (single value for regression)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim) # \n", + " self.layer4 = nn.Linear(hidden_dim,output_dim)\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", + " a3 =self.relu(self.layer3(a2))\n", + "\n", + " # TODO: Output layer (no activation for regression)\n", + " output = (self.layer4(a3)) # \n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # TODO: Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # TODO: Move batch to the selected device\n", + " # 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) # [HINT: reshape to (-1, 1)]\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # TODO: 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", + " # Calculate average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # TODO: Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # TODO: Disable gradient computation using torch.no_grad()\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # TODO: Move data to device\n", + " X_batch = X_batch.to(device) # \n", + " y_batch = y_batch.to(device) # [HINT: reshape to (-1, 1)]\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # \n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch) # \n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # \n", + "# Model parameters\n", + "input_dim = 36*3*36 # Number of tabular features\n", + "hidden_dim = 64\n", + "output_dim = 1\n", + "# TODO: Instantiate the model and move it to the device\n", + "model = NN4Layer(input_dim, hidden_dim,output_dim).to(device) # \n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss() # \n", + "\n", + "# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n", + "optimizer = AdamW(model.parameters(), learning_rate) #" + ], + "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", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "print(model)\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", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/368/Q3.ipynb b/submissions_extracted/368/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1c8be656cfb13a3586d1def33d058f41c1469471 --- /dev/null +++ b/submissions_extracted/368/Q3.ipynb @@ -0,0 +1,316 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# --- System & Utilities ---\n", + "import os\n", + "import warnings\n", + "from IPython.display import clear_output\n", + "from tqdm import tqdm\n", + "import kagglehub\n", + "\n", + "# --- Data Manipulation & Visualization ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Magic command for plotting\n", + "%matplotlib inline\n", + "# Filter warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# --- Machine Learning: Scikit-Learn ---\n", + "# Datasets\n", + "from sklearn.datasets import load_breast_cancer\n", + "\n", + "# Preprocessing\n", + "from sklearn.preprocessing import (\n", + " StandardScaler,\n", + " LabelEncoder,\n", + " OneHotEncoder,\n", + " MinMaxScaler\n", + ")\n", + "\n", + "# Model Selection\n", + "from sklearn.model_selection import (\n", + " train_test_split,\n", + " StratifiedKFold,\n", + " KFold,\n", + " cross_val_score\n", + ")\n", + "\n", + "# Metrics\n", + "from sklearn.metrics import (\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix, ConfusionMatrixDisplay,\n", + " mean_squared_error, mean_absolute_error, r2_score,\n", + " mean_squared_error as mse, mean_absolute_error as mae # Aliases used in notebook\n", + ")\n", + "\n", + "# Models: Linear & SVM\n", + "from sklearn.linear_model import (\n", + " LinearRegression,\n", + " LogisticRegression,\n", + " Ridge,\n", + " Lasso\n", + ")\n", + "from sklearn.svm import SVC, SVR\n", + "\n", + "# Models: Neighbors & Trees\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n", + "\n", + "# Models: Ensemble\n", + "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n", + "\n", + "# --- Machine Learning: Boosting Libraries ---\n", + "from xgboost import XGBClassifier\n", + "from lightgbm import LGBMRegressor\n", + "from catboost import CatBoostClassifier, CatBoostRegressor\n", + "\n", + "# --- Deep Learning: PyTorch ---\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# --- Computer Vision: TorchVision ---\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor" + ], + "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", + "# Load the dataset\n", + "food_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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", + "print(\"Missing Data Analysis:\")\n", + "# missing_data.head(10)\n", + "for col in df.columns:\n", + " df_clean[col] = df[col].fillna(\"unknown\")\n", + "df.head()\n", + "# df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: no need no objects" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "df_scale = scaler.fit_transform(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df.describe()# imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "X = df.drop(columns=[\"Target\"]).copy()\n", + "y=df[\"Target\"]\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1): #ماتفرق y\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "model = CatBoostClassifier(verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "model.fit(X_train,y_train)\n", + "y_pred = model.predict(X_test)\n", + "acc = accuracy_score(y_test,y_pred)\n", + "f1 = f1_score(y_test,y_pred)\n", + "print(\"Accuracy :\", acc)\n", + "print(\"F1 Score :\", f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#important how to compare\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'] = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(20, 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", + " 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/369/Q1.ipynb b/submissions_extracted/369/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfbb57e6de3e2bcf726ab5277182f076fbf38a8c --- /dev/null +++ b/submissions_extracted/369/Q1.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder ,OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\")\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", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, 'Delivery_Time')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': []}\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " rmse = np.sqrt(mse)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)" + ], + "execution_count": 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/369/Q2.ipynb b/submissions_extracted/369/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3815c01133c74b6f7dcfed4e8b2a271af5edf968 --- /dev/null +++ b/submissions_extracted/369/Q2.ipynb @@ -0,0 +1,377 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import kagglehub\n", + "import pandas as pd\n", + "import 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", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = X_train, y_train(\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 = X_test, y_test(\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": [ + "# 2. Create TensorDataset objects\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": [ + "# 3. Create DataLoaders\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": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class 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, 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", + " 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", + " 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", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " 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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 3 * 32 * 32\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "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/369/Q3.ipynb b/submissions_extracted/369/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..589c893be0e1e5e3c8ef903265b999432c783131 --- /dev/null +++ b/submissions_extracted/369/Q3.ipynb @@ -0,0 +1,293 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.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", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\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", + "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", + "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", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\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", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop('Target')\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, 'Target')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier" + ], + "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", + "# TODO: Define models with hyperparameters of your choice\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "results = {}\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n", + "\n", + "n_splits = 3 # K=3 Folds\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", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_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/37/Q1.ipynb b/submissions_extracted/37/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..147b4459f48a15efe74ce824f4016383afc5be90 --- /dev/null +++ b/submissions_extracted/37/Q1.ipynb @@ -0,0 +1,226 @@ +{ + "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", + "# 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 2: Write your code here:\n", + "print(\"head(rows)\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data info\n", + "\n", + "\"df_delivery.info(delivery)\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description\n", + "missing_percentage = (df_cars.isnull().sum() / len(df_cars)) * 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:\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#data not need to fix or Clean :)" + ], + "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", + "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", + "print(f\"\\ndelivrey ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)\n", + "#Train a RandomForest mode\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "#Evaluate using MAE (Mean Absolute Error) ONLY AND Print the averaged score across all folds\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 1: Write your code here:\n", + "#Plot feature importance from your trained model\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Plot predicted delivery time histogram\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/37/Q2.ipynb b/submissions_extracted/37/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..81dc485e1d41e1ba6fdb05352d0a4e7c9e6ddbab --- /dev/null +++ b/submissions_extracted/37/Q2.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "#Convert to PyTorch Tensors\n", + "x_half = x.to(torch.PyTorch Tensors)\n", + "print(x_half.dtype)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "x_gpu = x.to(device)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class 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 4\n", + " self.layer_1 = nn.Linear(input_dim, 1)\n", + " self.layer_2 = nn.Linear(input_dim, 2)\n", + " self.layer_3 = nn.Linear(input_dim, 3)\n", + " self.layer_4= nn.Linear(input_dim, 4)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + " self.relu = nn.ReLU()\n", + " self.sigmoid = nn.Sigmoid()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\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": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "ef 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.view(-1, 1).to(device)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "#to predictions with thur actul images\n", + "\n", + "model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\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/37/Q3.ipynb b/submissions_extracted/37/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a1732b742ee0ac7a409ccdffdf089434d21ffa52 --- /dev/null +++ b/submissions_extracted/37/Q3.ipynb @@ -0,0 +1,214 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"updated_pollution_dataset.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "path = kagglehub.dataset_download(\"mujtabamatin/air-quality-and-pollution-assessment\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: 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, \"Air Quality\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "y_pred = np.argmax(y_pred_proba, axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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": [ + "# Task 1: Write your code here:\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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": [ + "# Task Bonus: Write your code here:\n", + "results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/370/Q1.ipynb b/submissions_extracted/370/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b8d4680ace0fcc0bf43e64495010d4005c99fb94 --- /dev/null +++ b/submissions_extracted/370/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", + "# Load the dataset\n", + "import os\n", + "import pandas as pd\n", + "food_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(food_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", + "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", + " 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", + "\n", + "df.columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "\n", + "\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'].mean())\n", + "df['Delivery_Time'].fillna(df['Delivery_Time'].median())\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\n", + "\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):\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", + "print(\"Categorical columns:\", categorical_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\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", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']\n", + "lr_mae = []\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "model=RandomForestRegressor(n_estimators=200)\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", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\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" + ], + "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", + "\n", + "# Feature importance\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", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title(' predicted delivery time histogram')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/370/Q2.ipynb b/submissions_extracted/370/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f063f4286e1a558d37c601737e76c3372a31e262 --- /dev/null +++ b/submissions_extracted/370/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", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "from torchvision.transforms.functional import to_tensor\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", + "# Training dataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯ insaid nn.CrossEntropyLoss()\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36* 36\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 2\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "import torch.nn.functional as F\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# 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", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(2):\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/370/Q3.ipynb b/submissions_extracted/370/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..288b3f2c63a89498dd176957e4326f4615acd6af --- /dev/null +++ b/submissions_extracted/370/Q3.ipynb @@ -0,0 +1,290 @@ +{ + "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", + "# Load the dataset\n", + "import os\n", + "import pandas as pd\n", + "an_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(an_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 1: Write your code here:\n", + "#df.drop(columns=['D_142'])\n", + "#df.drop(columns=['D_42'])\n", + "#df.drop(columns=['D_137'])\n", + "#df.drop(columns=['D_138'])\n", + "stat_cols = ['D_142', 'D_42', 'D_137', 'D_138']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df.drop(columns=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", + "\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", + "#Encode categorical variables if needed ___ >> no needed\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\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", + "data_for_scale = df.drop(\"Target\", axis=1).astype(float)\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scalin" + ], + "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, \"Target\")\n", + "\n", + "#imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score , f1_score\n", + "from catboost import CatBoostRegressor\n", + "\n", + "model=CatBoostRegressor(verbose=0)\n", + "model.fit(X, y)\n", + "\n", + "acc1=[]\n", + "f1=[]\n", + "n_splits = 5 # K=5 Folds\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]\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", + " acc = accuracy_score(y_test, y_pred)\n", + "\n", + " F1_Scor = f1_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " acc1[model].append(acc)\n", + " f1[model].append(f1_score)\n", + "\n", + "print(f\" Accuracy: {acc1:.4f}\")\n", + " print(f\" F1-Score: {f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "importances = {}\n", + "importances['CatBoost'] = model['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", + "\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", + "importance = pd.DataFrame({\n", + " 'feature': df['golden feature'],\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='Blue')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X = X = df.drop(\"Target\", axis=1).astype(float)\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/371/Q1.ipynb b/submissions_extracted/371/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9bafb4f0fc6bae0104ca2f5e6d9b053f98dafa95 --- /dev/null +++ b/submissions_extracted/371/Q1.ipynb @@ -0,0 +1,321 @@ +{ + "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", + "Data = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "# read the file Q1_data.csv from the directory in the 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", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(Data['Delivery_Time'], bins=60, edgecolor='black')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Dellivr time')\n", + "plt.ylabel('Count')\n", + "plt.show()\n", + "\n", + "# Show the Distribution of the Target Label (i think it is a normal distribution so no need to transform the target)\n", + "# but thier some outleir" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Data.drop(columns='Order_ID',inplace=True)\n", + "Data.head(1)\n" + ], + "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(Data) # After checke missing value we can handling them by :\n", + "# First : Drop rows where target (Delivry Time) - can't predict without them\n", + "print(f\"Before: {Data.shape}\")\n", + "Data = Data.dropna(subset=['Delivery_Time'])\n", + "print(f\"After dropping missing Delivery_Time: {Data.shape}\")\n", + "\n", + "# Second : filling the missing value of weather,Traffic_level, Time_of_day ..elt\n", + "for col in ['Time_of_Day', 'Traffic_Level', 'Weather']:\n", + " Data[col] = Data[col].fillna('unknown')\n", + "Data['Courier_Experience_yrs'] = Data['Courier_Experience_yrs'].fillna(Data['Courier_Experience_yrs'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Handel duplecated sampel\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(Data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encodeng\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder,LabelEncoder\n", + "categorical_cols = ['Weather'\t,'Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " Data[col] = le.fit_transform(Data[col].astype(str))\n", + "\n", + "Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# prepearing data for scaling and model.\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "feature_cols = ['Distance_km' , 'Weather' ,'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'\n", + " ,'Preparation_Time_min' ,'Courier_Experience_yrs']\n", + "X = Data[feature_cols]\n", + "y = Data['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "# scaling the data :\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": [ + "# we don't need any type of Check for target imbalance because it is not Classification problem\n", + "# if it is we can do the suffeling to have better result." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# splited already befor scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predict and evaluate\n", + "from sklearn.metrics import mean_absolute_error\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: {mae:,.2f}\")" + ], + "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": [ + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_pred)], 'r--', linewidth=2)\n", + "\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/371/Q2.ipynb b/submissions_extracted/371/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/371/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/371/Q3.ipynb b/submissions_extracted/371/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bd0a613ef28efaffc50494823eb06bb794d3d7e5 --- /dev/null +++ b/submissions_extracted/371/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": [ + "import pandas as pd\n", + "Data = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(Data)\n", + "\n", + "# Fill missing values with mean for each column\n", + "Data = Data.fillna(Data.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Handel duplecated sampel\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": [ + "Data.info()\n", + "# all data from daata type int , float" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# prepearing data for scaling and model.\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = Data.drop(columns='Target')\n", + "y = Data['Target']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "# scaling the data :\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": [ + "import matplotlib.pyplot as plt\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " Data['Target'].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(Data, \"Target\")\n", + "\n", + "# Their is unbalenced data." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# splited already" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "\n", + "model = CatBoostClassifier() # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import accuracy_score, f1_score\n", + "import numpy as np\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + "print(\"F1 and Accurancy\")\n", + "print(f1)\n", + "print(accuracy)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': model.feature_names_,\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": [ + "feature_importance = pd.DataFrame({\n", + " 'feature': model.feature_names_,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "feature_importance\n", + "\n", + "#the golden feature is the P_2\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = Data['P_2']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\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/372/Q1.ipynb b/submissions_extracted/372/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ddd2f6ad218701c452bca7252ef1fc3c1fa494bd --- /dev/null +++ b/submissions_extracted/372/Q1.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "\n", + "\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", + "\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.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df,\"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " df=df.dropna(subset=['Delivery_Time'])\n", + " missing_values = df.isnull().sum()\n", + " print (missing_values)\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\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " onehot_encoder = OneHotEncoder()\n", + " df[col] = onehot_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", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "x = df.drop(\"Delivery_Time\", axis=1).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.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(x, y)):\n", + " X_train, X_test= x.ilo[train_index], x.ilo[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_fold_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_fold_pred))\n", + " model.fit(X_train,y_train)\n", + " y_pred = RandomForestRegressor.predict(X_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 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:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file