Spaces:
Sleeping
Sleeping
Commit ·
dc7dcab
1
Parent(s): 285f2e9
Added:Training Loop with Weights and Loss calculation for the model
Browse files7 unmodified lines8910111112131422 unmodified lines373839404140414243444 unmodified lines49505152525354559 unmodified lines656667686869707119 unmodified lines919293949495969798991001011021031041051061079798991001011131141021031041051061191201211221231241251071081091101111121131141151301311321331341351361371381161171181411191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481495 unmodified lines1551561571611621581591601611621631681641651661671681691701711721731731741751761761771781791801811821831841851861871881891901781911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372387 unmodified lines }, { "cell_type": "code", "execution_count": 11, "execution_count": null, "id": "51e70576", "metadata": {}, "outputs": [22 unmodified lines " 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", "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",4 unmodified lines }, { "cell_type": "code", "execution_count": 12, "execution_count": 17, "id": "6723a3ca", "metadata": {}, "outputs": [],9 unmodified lines }, { "cell_type": "code", "execution_count": null, "execution_count": 18, "id": "7c295080", "metadata": {}, "outputs": [19 unmodified lines }, { "cell_type": "code", "execution_count": null, "execution_count": 19, "id": "d9535811", "metadata": {}, "outputs": [], "source": [ "from torch.utils.data import DataLoader\n", "batch__size = 64\n" ] }, { "cell_type": "code", "execution_count": 15, "id": "5756ee9d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Moved X and Y label of training data to cuda successfully\n", "Moved X and Y label of testing data to cuda successfully\n" "Batches created for Train Data:140 and Test Data: 35\n" ] } ], "source": [ "#Moving the tensors to the device (GPU or CPU) for faster computing\n", "move_x_train = X_train.to(device) \n", "move_y_label = Y_train.to(device)\n", "print(f\"Moved X and Y label of training data to {device} successfully\") \n", "move_x_test = X_test.to(device)\n", "move_y_test = Y_test.to(device)\n", "print(f\"Moved X and Y label of testing data to {device} successfully\")" "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": null, "id": "26066eae", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 16, "execution_count": 20, "id": "41cfdb24", "metadata": {}, "outputs": [], "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",5 unmodified lines " #Output Layer\n", " self.out = nn.Linear(in_features = 32, out_features=7)\n", "\n", " def forward1(self,x):\n", " self.flatten = nn.Flatten()\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" " 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": null, "execution_count": 23, "id": "40d53a08", "metadata": {}, "outputs": [], "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" ] } ],PyTorchtrained.ipynb+99-42