{ "cells": [ { "cell_type": "markdown", "id": "9d0a3c0e", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": null, "id": "51e70576", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GPU is available\n", "Converting Arrays to Tensors . . . .\n", "torch.Size([11197, 150, 150, 3]) cpu\n", "torch.Size([11197]) cpu\n", "Tensors Created!\n" ] } ], "source": [ "\"\"\"1.This cell contains the code loading,checking and reshaping the dataset for further processing\"\"\" \n", "\n", "import torch \n", "import numpy as np\n", "\n", "#Loading Nmpy Arrays from the dataset\n", "raw = np.load(\"flowers_data.npy\")\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") #Fallback to CPU if GPU is not available\n", "if(device.type == \"cuda\"):\n", " print(\"GPU is available\")\n", " print(\"Converting Arrays to Tensors . . . .\")\n", " #Converting the numpy arrays to torch tensors for faster computing\n", "converted_x_label = torch.from_numpy(raw['X']).float() #W have converted to float because its necessary for further calculation accuracy\n", "converted_y_label = torch.from_numpy(raw['Y']).float()\n", "print(converted_x_label.shape,converted_x_label.device)\n", "print(converted_y_label.shape,converted_y_label.device)\n", "print(\"Tensors Created!\")\n", "\n", "#So the shape becomes (N, H, W, C) where N is the number of samples, H is the height of the image, W is the width of the image and C is the number of channels. But the model we are using expects the input shape to be (N, C, H, W). So we need to permute the dimensions of the tensor to match the input shape of the model.\n", "permuted = torch.permute(converted_x_label, (0, 3, 1, 2)) #Permuting the dimensions of the tensor to match the input shape of the model\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "6723a3ca", "metadata": {}, "outputs": [], "source": [ "\"\"\"This cell is used to shuffle the X and Y labels so that the model is \n", "actually learning and not memorizing the whole dataset\n", "\n", "\"\"\"\n", "indices = torch.randperm(len(permuted))\n", "X_shuffled = permuted[indices] / 255.0\n", "Y_shuffled = converted_y_label[indices].long().squeeze()\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "7c295080", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8957 8957 2240 2240\n" ] } ], "source": [ "#This cell splits the shuffled data into Training ans Test sets\n", "#80% of the data is used for training and 20% for testing\n", "train_split = int(0.8 * len(X_shuffled))\n", "X_train = X_shuffled[:train_split]\n", "Y_train = Y_shuffled[:train_split]\n", "X_test = X_shuffled[train_split:]\n", "Y_test = Y_shuffled[train_split:] \n", "print(len(X_train),len(Y_train),len(X_test),len(Y_test))\n", "\n" ] }, { "cell_type": "code", "execution_count": 19, "id": "d9535811", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Batches created for Train Data:140 and Test Data: 35\n" ] } ], "source": [ "from torch.utils.data import DataLoader,TensorDataset\n", "batch__size = 64\n", "train_loader = DataLoader(TensorDataset(X_train, Y_train), batch_size=batch__size, shuffle=True)\n", "test_loader = DataLoader(TensorDataset(X_test, Y_test), batch_size=batch__size, shuffle=False)\n", "print(f\"Batches created for Train Data:{len(train_loader)} and Test Data: {len(test_loader)}\")\n" ] }, { "cell_type": "code", "execution_count": 20, "id": "41cfdb24", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "FlowerClassifier(\n", " (flatten): Flatten(start_dim=1, end_dim=-1)\n", " (layer_1): Linear(in_features=67500, out_features=128, bias=True)\n", " (relu_1): ReLU()\n", " (layer_2): Linear(in_features=128, out_features=64, bias=True)\n", " (relu_2): ReLU()\n", " (layer_3): Linear(in_features=64, out_features=32, bias=True)\n", " (relu_3): ReLU()\n", " (out): Linear(in_features=32, out_features=7, bias=True)\n", ")\n" ] } ], "source": [ "from torch import nn\n", "import torch.optim as optim\n", "\n", "class FlowerClassifier(nn.Module):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " #Neural Network Initilization\n", " self.flatten = nn.Flatten()\n", "\n", " self.layer_1 = nn.Linear(in_features = 67500,out_features =128,bias=True)\n", " self.relu_1 = nn.ReLU()\n", " self.layer_2 = nn.Linear(in_features=128,out_features=64,bias=True)\n", " self.relu_2 = nn.ReLU()\n", " self.layer_3 = nn.Linear(in_features=64,out_features=32,bias=True)\n", " self.relu_3 = nn.ReLU()\n", "\n", " #Output Layer\n", " self.out = nn.Linear(in_features = 32, out_features=7)\n", "\n", " def forward(self,x):\n", " x = self.flatten(x)\n", " x = self.relu_1(self.layer_1(x))\n", " x = self.relu_2(self.layer_2(x))\n", " x = self.relu_3(self.layer_3(x))\n", " x = self.out(x)\n", " return x\n", "\n", "model = FlowerClassifier().to(device)\n", "loss_function = nn.CrossEntropyLoss()\n", "optimizer = optim.Adam(model.parameters(), lr=0.001)\n", "print(model)" ] }, { "cell_type": "code", "execution_count": 23, "id": "40d53a08", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'running_train_loss' is not defined", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[23]\u001b[39m\u001b[32m, line 13\u001b[39m\n\u001b[32m 9\u001b[39m loss = loss_function(output, labels)\n\u001b[32m 10\u001b[39m optimizer.zero_grad()\n\u001b[32m 11\u001b[39m loss.backward()\n\u001b[32m 12\u001b[39m optimizer.step()\n\u001b[32m---> \u001b[39m\u001b[32m13\u001b[39m train_loss = running_train_loss / total_train\n\u001b[32m 14\u001b[39m train_acc = (correct_train / total_train) * \u001b[32m100\u001b[39m\n\u001b[32m 15\u001b[39m \n\u001b[32m 16\u001b[39m \u001b[38;5;66;03m# ==========================\u001b[39;00m\n", "\u001b[31mNameError\u001b[39m: name 'running_train_loss' is not defined" ] } ], "source": [ "epochs = 20\n", "for i in range(epochs):\n", " for images, labels in train_loader:\n", " images = images.to(device)\n", " labels = labels.to(device)\n", "\n", " # Forward Pass\n", " output = model(images)\n", " loss = loss_function(output, labels)\n", " optimizer.zero_grad()\n", " loss.backward()\n", " optimizer.step()\n", "train_loss = running_train_loss / total_train\n", "train_acc = (correct_train / total_train) * 100\n", "\n", " # ==========================\n", " # 2. TESTING (Every Epoch)\n", " # ==========================\n", "model.eval() # Freeze layers for evaluation\n", "running_test_loss = 0.0\n", "correct_test = 0\n", "total_test = 0\n", "\n", "with torch.inference_mode(): # Disable Autograd to save VRAM and time\n", " for images, labels in test_loader:\n", " images = images.to(device)\n", " labels = labels.to(device)\n", "\n", " test_outputs = model(images)\n", " t_loss = loss_function(test_outputs, labels)\n", "\n", " running_test_loss += t_loss.item() * images.size(0)\n", " _, test_preds = torch.max(test_outputs, 1)\n", " correct_test += (test_preds == labels).sum().item()\n", " total_test += labels.size(0)\n", "\n", "test_loss = running_test_loss / total_test\n", "test_acc = (correct_test / total_test) * 100\n", "\n", " # ==========================\n", " # 3. PRINT PROGRESS\n", " # ==========================\n", "print(f\"Epoch [{epoch+1:02d}/{epochs:02d}] | \"\n", " f\"Train Loss: {train_loss:.4f} | Train Acc: {train_acc:.2f}% | \"\n", " f\"Test Loss: {test_loss:.4f} | Test Acc: {test_acc:.2f}%\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.7" } }, "nbformat": 4, "nbformat_minor": 5 }