{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Assess predictions on object detection fridge data with a pytorch model" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "This notebook demonstrates the use of the `responsibleai` API to assess an object detection pytorch model trained on the fridge dataset. It walks through the API calls necessary to create a widget with model analysis insights, then guides a visual analysis of the model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Launch Responsible AI Toolbox" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following section examines the code necessary to create datasets and a model. It then generates insights using the `responsibleai` API that can be visually analyzed." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Load Model and Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "from zipfile import ZipFile\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib\n", "matplotlib.use('Agg')\n", "import matplotlib.pyplot as plt\n", "from responsibleai_vision.common.constants import ImageColumns\n", "\n", "import os\n", "import xml.etree.ElementTree as ET\n", "\n", "try:\n", " from urllib import urlretrieve\n", "except ImportError:\n", " from urllib.request import urlretrieve\n", "\n", "EPOCHS = 10\n", "LEARNING_RATE = 1e-4\n", "IM_SIZE = 300\n", "BATCH_SIZE = 16\n", "FRIDGE_MODEL_NAME = 'fridge_od_model'\n", "FRIDGE_MODEL_WINDOWS_NAME = 'fridge_model_windows'\n", "WIN = 'win'\n", "\n", "def load_fridge_object_detection_dataset_labels():\n", "\n", " src_images = \"./data/odFridgeObjects/\"\n", "\n", " # Path to the annotations\n", " annotations_folder = os.path.join(src_images, \"annotations\")\n", " \n", " labels = []\n", " label_dict = {'can': 1, 'carton': 2, 'milk_bottle': 3, 'water_bottle': 4}\n", " \n", " # Read each annotation\n", " for i, filename in enumerate(os.listdir(annotations_folder)):\n", " if filename.endswith(\".xml\"):\n", " print(\"Parsing \" + os.path.join(src_images, filename))\n", "\n", " root = ET.parse(os.path.join(annotations_folder, filename)).getroot()\n", "\n", " # use if needed\n", " # width = int(root.find(\"size/width\").text)\n", " # height = int(root.find(\"size/height\").text)\n", "\n", " image_labels = []\n", " for object in root.findall(\"object\"):\n", " name = object.find(\"name\").text\n", " xmin = object.find(\"bndbox/xmin\").text\n", " ymin = object.find(\"bndbox/ymin\").text\n", " xmax = object.find(\"bndbox/xmax\").text\n", " ymax = object.find(\"bndbox/ymax\").text\n", " isCrowd = int(object.find(\"difficult\").text)\n", " image_labels.append([\n", " label_dict[name], # label\n", " float(xmin), # topX. To normalize, divide by width.\n", " float(ymin), # topY. To normalize, divide by height.\n", " float(xmax), # bottomX. To normalize, divide by width\n", " float(ymax), # bottomY. To normalize, divide by height\n", " int(isCrowd)\n", " ])\n", " labels.append(image_labels)\n", " \n", " return labels\n", "\n", "def load_fridge_object_detection_dataset():\n", " # create data folder if it doesnt exist.\n", " os.makedirs(\"data\", exist_ok=True)\n", "\n", " # download data\n", " download_url = (\"https://cvbp-secondary.z19.web.core.windows.net/\" +\n", " \"datasets/object_detection/odFridgeObjects.zip\")\n", " data_file = \"./odFridgeObjects.zip\"\n", " urlretrieve(download_url, filename=data_file)\n", "\n", " # extract files\n", " with ZipFile(data_file, \"r\") as zip:\n", " print(\"extracting files...\")\n", " zip.extractall(path=\"./data\")\n", " print(\"done\")\n", " # delete zip file\n", " os.remove(data_file)\n", " \n", " \n", " labels = load_fridge_object_detection_dataset_labels()\n", " \n", " feats = []\n", " for i, file in enumerate(os.listdir(\"./data/odFridgeObjects/\" + \"images\")):\n", " image_path = \"./data/odFridgeObjects/\" + \"images\" + \"/\" + file\n", " feats.append({ImageColumns.IMAGE.value: image_path,\n", " ImageColumns.LABEL.value: labels[i]})\n", " \n", " # get all file names into a pandas dataframe with the labels\n", " data = pd.DataFrame(feats, columns=[ImageColumns.IMAGE.value,\n", " ImageColumns.LABEL.value])\n", " \n", " \n", " return data" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Load Pretrained Faster RCNN model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import urllib.request as request_file\n", "\n", "#download fine-tuned recycling model from url\n", "def download_assets(filepath,force=False):\n", " if force or not os.path.exists(filepath):\n", " request_file.urlretrieve(\n", " \"https://publictestdatasets.blob.core.windows.net/models/fastrcnn.pt\",\n", " os.path.join(filepath))\n", " else:\n", " print('Found ' + filepath)\n", "\n", " return filepath" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Loading in our pretrained model \n", "import torchvision\n", "from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n", "from torchvision.models.detection.faster_rcnn import FasterRCNN_ResNet50_FPN_Weights\n", "import torch\n", "import os\n", "\n", "def get_instance_segmentation_model(num_classes):\n", " # load an instance segmentation model pre-trained on COCO\n", " model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1)\n", " in_features = model.roi_heads.box_predictor.cls_score.in_features\n", " # replace the pre-trained head with a new one\n", " model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n", " return model\n", "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", "\n", "print('Device: ', str(device))\n", "\n", "num_classes = 5\n", "model = get_instance_segmentation_model(num_classes)\n", "_ = download_assets('Recycling_finetuned_FastRCNN.pt')\n", "model.load_state_dict(torch.load('Recycling_finetuned_FastRCNN.pt', map_location = device))\n", "\n", "#if using the general torchvision pretrained model, comment above and uncomment below\n", "# model = detection.fasterrcnn_resnet50_fpn(pretrained=True)\n", "\n", "model.to(device)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = load_fridge_object_detection_dataset()\n", "\n", "train_data = data\n", "test_data = data\n", "class_names = np.array(['can', 'carton', 'milk_bottle', 'water_bottle'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create Model and Data Insights" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from raiwidgets import ResponsibleAIDashboard\n", "from responsibleai_vision import ModelTask, RAIVisionInsights" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "To use Responsible AI Toolbox, initialize a RAIInsights object upon which different components can be loaded.\n", "\n", "RAIInsights accepts the model, the full dataset, the test dataset, the target feature string and the task type string as its arguments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rai_insights = RAIVisionInsights(model, test_data.sample(5, random_state=42),\n", " \"label\",\n", " task_type=ModelTask.OBJECT_DETECTION,\n", " classes=class_names)\n", "\n", "rai_insights" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Add the components of the toolbox that are focused on model assessment." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Interpretability\n", "rai_insights.explainer.add()\n", "# Error Analysis\n", "rai_insights.error_analysis.add()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once all the desired components have been loaded, compute insights on the test set." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rai_insights.compute()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, visualize and explore the model insights. Use the resulting widget or follow the link to view this in a new tab." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ResponsibleAIDashboard(rai_insights)" ] } ], "metadata": { "kernelspec": { "display_name": "raivision", "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.8.17" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "053dc3c540a9260e9464092636530e4f43e21211e2a5bed21a6f6ec172233695" } } }, "nbformat": 4, "nbformat_minor": 2 }