{ "cells": [ { "cell_type": "markdown", "id": "da0e7c96", "metadata": {}, "source": [ "# Tutorial: Building deep learning models using eo4wildfires dataset, huggingface's transformers and PyTorch models\n", "\n", "Before we proceed, assuming the new Python3 changes, we need to install and activate a virtual environment for the libraries that we are going to use in this tutorial. Please check README.md of this project, for more information. After all libraries are installed, we simply import the eo4wildfires dataset directly from huggingface, during the prompt \"Do you wish to run the custom code?\" type \"y\" and press Enter (before typing \"y\" you should review the dataloading code at https://huggingface.co/datasets/AUA-Informatics-Lab/eo4wildfires/blob/main/eo4wildfires.py).\n", "\n", "\n", "This should take a moment, depending on your connection. It should begin downloading the zip archive of the dataset and then extract it. After extraction, train/test/validation splits are automatically calculated and converted into pyarrow format, for more efficient loading. Note that only the first time should take a while, after that dataset should load within seconds." ] }, { "cell_type": "code", "execution_count": 1, "id": "1cbd9cfc", "metadata": { "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "154bbd34dbae416d909440ecc112f318", "version_major": 2, "version_minor": 0 }, "text/plain": [ "README.md: 0%| | 0.00/3.75k [00:00" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import matplotlib.pyplot as plt\n", "\n", "fig, axes = plt.subplots(3, 2, figsize=(12, 20))\n", "\n", "axes[0][0].imshow(dataset['validation'][0]['burned_mask']*255)\n", "axes[0][1].imshow((dataset['validation'][0]['S2A'][3:0:-1]*255).astype('int').transpose(1, 2, 0))\n", "\n", "axes[1][0].imshow(dataset['validation'][16]['burned_mask']*255)\n", "axes[1][1].imshow((dataset['validation'][16]['S2A'][3:0:-1]*255).astype('int').transpose(1, 2, 0))\n", "\n", "axes[2][0].imshow(dataset['validation'][789]['burned_mask']*255)\n", "axes[2][1].imshow((dataset['validation'][789]['S2A'][3:0:-1]*255).astype('int').transpose(1, 2, 0))\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "bbadbecf", "metadata": {}, "source": [ "## Train using huggingface library" ] }, { "cell_type": "markdown", "id": "b5bbf827", "metadata": {}, "source": [ "For this tutorial, we are going to use Sentinel 1 GRD Ascending data (bands VV, VH, (VV - VH) / (VV + VH)) as an input RGB image.\n", "\n", "First we load an Image Processor, since we only have 2 classes (0 for background and 1 for wildfire) we need to use do_reduce_labels=True, as suggested by the docs. We are not going to use any image augmentation." ] }, { "cell_type": "code", "execution_count": 6, "id": "107ced5e", "metadata": {}, "outputs": [], "source": [ "from transformers import AutoImageProcessor\n", "image_processor = AutoImageProcessor.from_pretrained('nvidia/mit-b0', do_reduce_labels=True)" ] }, { "cell_type": "code", "execution_count": 7, "id": "1097cc8d", "metadata": {}, "outputs": [], "source": [ "def _transforms(example_batch):\n", " # print(example_batch['S1_GRD_A'][0])\n", " # Convert S1A into PIL Image objects\n", " images = [np.asarray(x)[3:0:-1].astype('int') for x in example_batch['S2A']]\n", " labels = [np.asarray(x) for x in example_batch['burned_mask']]\n", " inputs = image_processor(images, labels)\n", " return inputs\n", "\n", "train_ds = dataset['train']\n", "val_ds = dataset['validation']\n", "test_ds = dataset['test']\n", "\n", "val_ds.set_transform(_transforms)\n", "train_ds.set_transform(_transforms)\n", "test_ds.set_transform(_transforms)" ] }, { "cell_type": "code", "execution_count": 8, "id": "2cfba99d", "metadata": {}, "outputs": [], "source": [ "import evaluate\n", "\n", "metric = evaluate.load(\"mean_iou\")\n", "\n", "id2label = {0: 'wildfire'}\n", "label2id = {'wildfire': 0}" ] }, { "cell_type": "code", "execution_count": 9, "id": "85856200", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import torch\n", "from torch import nn\n", "\n", "def compute_metrics(eval_pred):\n", " with torch.no_grad():\n", " logits, labels = eval_pred\n", " logits_tensor = torch.from_numpy(logits)\n", " logits_tensor = nn.functional.interpolate(\n", " logits_tensor,\n", " size=labels.shape[-2:],\n", " mode=\"bilinear\",\n", " align_corners=False,\n", " ).argmax(dim=1)\n", "\n", " pred_labels = logits_tensor.detach().cpu().numpy()\n", " metrics = metric.compute(\n", " predictions=pred_labels,\n", " references=labels,\n", " num_labels=num_labels,\n", " ignore_index=255,\n", " reduce_labels=False,\n", " )\n", " for key, value in metrics.items():\n", " if isinstance(value, np.ndarray):\n", " metrics[key] = value.tolist()\n", " return metrics" ] }, { "cell_type": "code", "execution_count": 10, "id": "42fd39fc", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of SegformerForSemanticSegmentation were not initialized from the model checkpoint at nvidia/mit-b0 and are newly initialized: ['decode_head.batch_norm.bias', 'decode_head.batch_norm.num_batches_tracked', 'decode_head.batch_norm.running_mean', 'decode_head.batch_norm.running_var', 'decode_head.batch_norm.weight', 'decode_head.classifier.bias', 'decode_head.classifier.weight', 'decode_head.linear_c.0.proj.bias', 'decode_head.linear_c.0.proj.weight', 'decode_head.linear_c.1.proj.bias', 'decode_head.linear_c.1.proj.weight', 'decode_head.linear_c.2.proj.bias', 'decode_head.linear_c.2.proj.weight', 'decode_head.linear_c.3.proj.bias', 'decode_head.linear_c.3.proj.weight', 'decode_head.linear_fuse.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] } ], "source": [ "from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer\n", "\n", "model = AutoModelForSemanticSegmentation.from_pretrained(\"nvidia/mit-b0\", id2label=id2label, label2id=label2id)" ] }, { "cell_type": "code", "execution_count": 11, "id": "2280af44", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "max_steps is given, it will override any value given in num_train_epochs\n", "It looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\n" ] }, { "data": { "text/html": [ "\n", "
\n", " \n", " \n", " [1/1 00:00, Epoch 0/1]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation Loss

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "TrainOutput(global_step=1, training_loss=0.19473744928836823, metrics={'train_runtime': 0.8294, 'train_samples_per_second': 2.411, 'train_steps_per_second': 1.206, 'total_flos': 35053485686784.0, 'train_loss': 0.19473744928836823, 'epoch': 6.40450877417702e-05})" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "training_args = TrainingArguments(\n", " output_dir='segformer-b0-scene-parse-150',\n", " learning_rate=6e-5,\n", " num_train_epochs=50,\n", " per_device_train_batch_size=2,\n", " per_device_eval_batch_size=2,\n", " save_total_limit=3,\n", " eval_strategy='steps',\n", " save_strategy='steps',\n", " save_steps=20,\n", " eval_steps=20,\n", " logging_steps=1,\n", " eval_accumulation_steps=5,\n", " remove_unused_columns=False,\n", " \n", " # turnoff wandb\n", " report_to='none',\n", " \n", " # train on 1 batch\n", " max_steps=1\n", ")\n", "\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=train_ds,\n", " eval_dataset=test_ds,\n", " compute_metrics=compute_metrics,\n", ")\n", "\n", "trainer.train()" ] }, { "cell_type": "markdown", "id": "4242d5c5", "metadata": {}, "source": [ "## Train using PyTorch" ] }, { "cell_type": "code", "execution_count": 12, "id": "a286f1b7", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "946bc27421e84ba9a6f2cdd3f8185c05", "version_major": 2, "version_minor": 0 }, "text/plain": [ "README.md: 0%| | 0.00/3.96k [00:00