{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Example\n", "=======\n", "\n", "As a first example, we use an image dataset and a pre-trained model to classify the images. We use the `ReVel` framework to load the dataset and the model, and to perform the classification. We also added the `procedures` module to help us with the classification process." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from torch.utils.data import random_split\n", "import torch.nn.functional as F\n", "from torch.utils.data import DataLoader\n", "from ReVel.perturbations import get_perturbation\n", "from ReVel.load_data import load_data\n", "from TSHIELD import TSHIELD\n", "from TSHIELD.procedures import procedures\n", "\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "# Load the model\n", "# Download the dataset Flowers and change the last layer to fit the number of classes\n", "classifier = procedures.classifier(\"efficientnet-b2\", num_classes=102)\n", "perturbation = get_perturbation(name=\"square\",dim=9,num_classes= 102,\n", " final_size=(224, 224),kernel=150.0,max_dist=20,ratio=0.5)\n", "\n", "train_set = load_data(\"Flowers\", perturbation=perturbation, train=True, dir=\"./data/\")\n", "test_set = load_data(\"Flowers\", perturbation=perturbation, train=False, dir=\"./data/\")\n", "classifier.to(device)\n", "\n", "Train, Val = random_split(\n", " train_set, [int(len(train_set) * 0.9), len(train_set) - int(len(train_set) * 0.9)]\n", ")\n", "# Subset of 5% of train and 5% of val\n", "\n", "Train = torch.utils.data.Subset(Train, range(int(len(Train) * 0.05)))\n", "Val = torch.utils.data.Subset(Val, range(int(len(Val) * 0.05)))\n", "\n", "TrainLoader = DataLoader(Train, batch_size=32, shuffle=True)\n", "ValLoader = DataLoader(Val, batch_size=32, shuffle=False)\n", "\n", "def loss_f(y_pred,y_label):\n", " return F.cross_entropy(y_pred,torch.argmax(y_label,dim=1))\n", "optimizer = torch.optim.AdamW(classifier.parameters(), lr=0.001,\n", " weight_decay=0.01, amsgrad=True)\n", "epochs = 5 # Change the number of epochs in case you need more\n", "best_loss = torch.tensor(float(\"inf\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Training and validation phase\n", "=============================" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch :1, 20.00%\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Training: 0%| | 0/3 [00:00