{ "cells": [ { "cell_type": "markdown", "id": "2e3e807d", "metadata": {}, "source": [ "# Multimodal Cancer Detection using the Intel® Transfer Learning Tool API\n", "\n", "This application is a multimodal solution for predicting cancer diagnosis using categorized contrast enhanced mammography data and radiology notes. It trains two models - one for image classification and the other for text classification - which can be combined into an ensemble classifier.\n", "\n", "## Import Dependencies and Setup Directories" ] }, { "cell_type": "code", "execution_count": null, "id": "f2a722a7", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import os\n", "import pandas as pd\n", "import tensorflow as tf\n", "import torch\n", "\n", "from transformers import EvalPrediction, TrainingArguments\n", "\n", "# tlt imports\n", "from tlt.datasets import dataset_factory\n", "from tlt.models import model_factory\n", "\n", "# Specify the root directory where the images and annotations are located\n", "dataset_dir = os.path.join(os.environ[\"DATASET_DIR\"]) if \"DATASET_DIR\" in os.environ else \\\n", " os.path.join(os.environ[\"HOME\"], \"dataset\")\n", "\n", "# Specify a directory for output\n", "output_dir = os.environ[\"OUTPUT_DIR\"] if \"OUTPUT_DIR\" in os.environ else \\\n", " os.path.join(os.environ[\"HOME\"], \"output\")\n", "\n", "print(\"Dataset directory:\", dataset_dir)\n", "print(\"Output directory:\", output_dir)" ] }, { "cell_type": "markdown", "id": "bb53162b", "metadata": {}, "source": [ "## Dataset\n", "\n", "Download the images and radiology annotations from https://wiki.cancerimagingarchive.net/pages/viewpage.action?pageId=109379611\n", "\n", "Image files should have the .jpg extension and be arranged in subfolders for each class. The annotation file should be a .csv. The data directory should look something like this:\n", "\n", "```\n", "brca\n", " ├── annotation\n", " │ └── annotation.csv\n", " └── vision_images\n", " ├── Benign\n", " │ ├── P100_L_CM_CC.jpg\n", " │ ├── P100_L_CM_MLO.jpg\n", " │ └── ...\n", " ├── Malignant\n", " │ ├── P102_R_CM_CC.jpg\n", " │ ├── P102_R_CM_MLO.jpg\n", " │ └── ...\n", " └── Normal\n", " ├── P100_R_CM_CC.jpg\n", " ├── P100_R_CM_MLO.jpg\n", " └── ...\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "bd9c3ef2", "metadata": {}, "outputs": [], "source": [ "# User input needed - supply the path to the images in the dataset_dir according to your system\n", "source_image_path = os.path.join(dataset_dir, 'brca', 'vision_images')\n", "image_path = source_image_path\n", "\n", "# User input needed - supply the path and name of the annotation file in the dataset_dir\n", "source_annotation_path = os.path.join(dataset_dir, 'brca', 'annotation', 'annotation.csv')\n", "annotation_path = source_annotation_path\n", "label_col = 3 # Index of the label column in the data file" ] }, { "cell_type": "markdown", "id": "245df47c", "metadata": {}, "source": [ "### Optional: Group Data by Patient ID\n", "\n", "This section is not required to run the workload, but it is helpful to assign all of a subject's records to be entirely in the train set or test set. This section will do a random stratification based on patient ID and save new copies of the grouped data files." ] }, { "cell_type": "code", "execution_count": null, "id": "44dbd990", "metadata": {}, "outputs": [], "source": [ "from data_utils import split_images, split_annotation\n", "\n", "grouped_image_path = '{}_grouped'.format(source_image_path)\n", "\n", "if os.path.isdir(grouped_image_path):\n", " print(\"Grouped directory already exists and will be used: {}\".format(grouped_image_path))\n", "else:\n", " split_images(source_image_path, grouped_image_path)\n", "\n", "image_path = grouped_image_path" ] }, { "cell_type": "code", "execution_count": null, "id": "0d21bdff", "metadata": {}, "outputs": [], "source": [ "file_dir, file_name = os.path.split(source_annotation_path)\n", "grouped_annotation_path = os.path.join(file_dir, '{}_grouped.csv'.format(os.path.splitext(file_name)[0]))\n", "\n", "if os.path.isfile(grouped_annotation_path):\n", " print(\"Grouped annotation already exists and will be used: {}\".format(grouped_annotation_path))\n", "else:\n", " train_dataset = split_annotation(file_dir, file_name, image_path)\n", " train_dataset.to_csv(grouped_annotation_path)\n", " print('Grouped annotation saved to: {}'.format(grouped_annotation_path))\n", "\n", "annotation_path = grouped_annotation_path\n", "label_col = 1 # Index of the label column in the grouped data file" ] }, { "cell_type": "markdown", "id": "01e9e5cf", "metadata": {}, "source": [ "## Model 1: Image Classification with TensorFlow\n", "\n", "### Get the Model and Dataset\n", "Call the model factory to get a pretrained model from TensorFlow Hub and the dataset factory to load the images from their location. The `get_model` function returns a model object that will later be used for training. We will use resnet_v1_50 by default." ] }, { "cell_type": "code", "execution_count": null, "id": "d9c93b18", "metadata": {}, "outputs": [], "source": [ "model = model_factory.get_model(model_name=\"resnet_v1_50\", framework='tensorflow')\n", "\n", "# Load the dataset from the custom dataset path\n", "dataset = dataset_factory.load_dataset(dataset_dir=image_path,\n", " use_case='image_classification',\n", " framework='tensorflow')\n", "\n", "print(\"Class names:\", str(dataset.class_names))" ] }, { "cell_type": "markdown", "id": "6472bedd", "metadata": {}, "source": [ "### Data Preparation\n", "Once you have your dataset loaded, use the following cell to preprocess the dataset. We split the images into training and validation subsets, resize them to match the model, and then batch the images." ] }, { "cell_type": "code", "execution_count": null, "id": "98dcf057", "metadata": {}, "outputs": [], "source": [ "batch_size = 16\n", "if 'grouped' not in image_path:\n", " # Split if not pre-defined\n", " dataset.shuffle_split(train_pct=.80, val_pct=0.0, test_pct=0.2)\n", "dataset.preprocess(model.image_size, batch_size=batch_size)" ] }, { "cell_type": "markdown", "id": "f2f49c77", "metadata": {}, "source": [ "### Transfer Learning\n", "\n", "This step calls the model's train function with the dataset that was just prepared. The training function will get the TFHub feature vector and add on a dense layer based on the number of classes in the dataset. The model is then compiled and trained based on the number of epochs specified in the argument. We also add two more dense layers using the `extra_layers` parameter.\n", "\n", "To optionally insert additional dense layers between the base model and output layer, `extra_layers=[1024, 512]` will insert two dense layers, the first with 1024 neurons and the second with 512 neurons." ] }, { "cell_type": "code", "execution_count": null, "id": "21a92e4e", "metadata": {}, "outputs": [], "source": [ "history = model.train(dataset, output_dir=output_dir, epochs=5, seed=10, extra_layers=[1024, 512], do_eval=False)" ] }, { "cell_type": "code", "execution_count": null, "id": "45289d48", "metadata": {}, "outputs": [], "source": [ "metrics = model.evaluate(dataset, use_test_set=True)\n", "for metric_name, metric_value in zip(model._model.metrics_names, metrics):\n", " print(\"{}: {}\".format(metric_name, metric_value))" ] }, { "cell_type": "markdown", "id": "bce6bafe", "metadata": {}, "source": [ "### Save the Computer Vision Model" ] }, { "cell_type": "code", "execution_count": null, "id": "093905b2", "metadata": {}, "outputs": [], "source": [ "saved_model_dir = model.export(output_dir)" ] }, { "cell_type": "markdown", "id": "5621b571", "metadata": {}, "source": [ "## Model 2: Text Classification with PyTorch\n", "\n", "### Get the Model and Dataset\n", "Now we will call the model factory to get a pretrained model from Hugging Face and load the annotation file using the dataset factory. We will use clinical-bert for this part." ] }, { "cell_type": "code", "execution_count": null, "id": "d18cebff", "metadata": {}, "outputs": [], "source": [ "# Set up NLP parameters\n", "model_name = 'clinical-bert'\n", "seq_length = 64\n", "batch_size = 5\n", "quantization_criterion = 0.05\n", "quantization_max_trial = 50\n", "epochs = 3" ] }, { "cell_type": "code", "execution_count": null, "id": "d939924f", "metadata": {}, "outputs": [], "source": [ "model = model_factory.get_model(model_name=model_name, framework='pytorch')" ] }, { "cell_type": "code", "execution_count": null, "id": "2e9dff00", "metadata": {}, "outputs": [], "source": [ "# Create a label map function and reverse label map for the dataset\n", "def label_map_func(label):\n", " if label == 'Benign':\n", " return 0\n", " elif label == 'Malignant':\n", " return 1\n", " elif label == 'Normal':\n", " return 2\n", " \n", "reverse_label_map = {0: 'Benign', 1: 'Malignant', 2: 'Normal'}" ] }, { "cell_type": "code", "execution_count": null, "id": "879bad74", "metadata": {}, "outputs": [], "source": [ "file_dir, file_name = os.path.split(annotation_path)\n", "dataset = dataset_factory.load_dataset(dataset_dir=file_dir,\n", " use_case='text_classification',\n", " framework='pytorch',\n", " dataset_name='brca',\n", " csv_file_name=file_name,\n", " label_map_func=label_map_func,\n", " class_names=['Benign', 'Malignant', 'Normal'],\n", " header=True,\n", " label_col=label_col,\n", " shuffle_files=True)" ] }, { "cell_type": "markdown", "id": "e2b9ddba", "metadata": {}, "source": [ "### Data Preparation" ] }, { "cell_type": "code", "execution_count": null, "id": "b166b757", "metadata": {}, "outputs": [], "source": [ "dataset.preprocess(model.hub_name, batch_size=batch_size, max_length=seq_length)\n", "dataset.shuffle_split(train_pct=0.67, val_pct=0.33)" ] }, { "cell_type": "markdown", "id": "020303ee", "metadata": {}, "source": [ "### Transfer Learning\n", "\n", "This step calls the model's train function with the dataset that was just prepared. The training function will get the pretrained model from HuggingFace and add on a dense layer based on the number of classes in the dataset. The model is then trained using an instance of Hugging Face Trainer for the number of epochs specified. If desired, a native PyTorch loop can be invoked instead of Trainer by setting `use_trainer=False`." ] }, { "cell_type": "code", "execution_count": null, "id": "41fb0612", "metadata": {}, "outputs": [], "source": [ "history = model.train(dataset, output_dir, epochs=epochs, use_trainer=True)" ] }, { "cell_type": "markdown", "id": "de70a029", "metadata": {}, "source": [ "### Save the NLP Model" ] }, { "cell_type": "code", "execution_count": null, "id": "ba08847d", "metadata": {}, "outputs": [], "source": [ "model.export(output_dir)" ] }, { "cell_type": "markdown", "id": "45752dd6", "metadata": {}, "source": [ "### Int8 Quantization\n", "\n", "We can use the [Intel® Extension for Transformers](https://github.com/intel/intel-extension-for-transformers) to quantize the trained model for faster inference. If you want to run this part of the notebook, make sure you have `intel-extension-for-transformers` installed in your environment." ] }, { "cell_type": "code", "execution_count": null, "id": "44036b44", "metadata": {}, "outputs": [], "source": [ "!pip install intel-extension-for-transformers==1.0.1" ] }, { "cell_type": "code", "execution_count": null, "id": "ce0687ce", "metadata": {}, "outputs": [], "source": [ "from intel_extension_for_transformers.optimization.trainer import NLPTrainer\n", "from intel_extension_for_transformers.optimization import metrics, objectives, OptimizedModel, QuantizationConfig" ] }, { "cell_type": "code", "execution_count": null, "id": "f9557a68", "metadata": {}, "outputs": [], "source": [ "# Set up quantization config\n", "tune_metric = metrics.Metric(\n", " name=\"eval_accuracy\",\n", " greater_is_better=True,\n", " is_relative=True,\n", " criterion=quantization_criterion,\n", " weight_ratio=None,\n", ")\n", "\n", "objective = objectives.Objective(\n", " name=\"performance\", greater_is_better=True, weight_ratio=None\n", ")\n", "\n", "quantization_config = QuantizationConfig(\n", " approach=\"PostTrainingDynamic\",\n", " max_trials=quantization_max_trial,\n", " metrics=[tune_metric],\n", " objectives=[objective],\n", ")\n", "\n", "# Set up metrics computation\n", "def compute_metrics(p: EvalPrediction):\n", " preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions\n", " preds = np.argmax(preds, axis=1)\n", " return {\"accuracy\": (preds == p.label_ids).astype(np.float32).mean().item()}" ] }, { "cell_type": "code", "execution_count": null, "id": "f406d6db", "metadata": {}, "outputs": [], "source": [ "quantizer = NLPTrainer(model=model._model,\n", " train_dataset=dataset.train_subset,\n", " eval_dataset=dataset.validation_subset,\n", " compute_metrics=compute_metrics,\n", " tokenizer=dataset._tokenizer)\n", "quantized_model = quantizer.quantize(quant_config=quantization_config)" ] }, { "cell_type": "code", "execution_count": null, "id": "56e5f2f5", "metadata": {}, "outputs": [], "source": [ "results = quantizer.evaluate()\n", "eval_acc = results.get(\"eval_accuracy\")\n", "print(\"Final Eval Accuracy: {:.5f}\".format(eval_acc))" ] }, { "cell_type": "markdown", "id": "b69df1a0", "metadata": {}, "source": [ "## Citations\n", "\n", "### Data Citation\n", "Khaled R., Helal M., Alfarghaly O., Mokhtar O., Elkorany A., El Kassas H., Fahmy A. Categorized Digital Database for Low energy and Subtracted Contrast Enhanced Spectral Mammography images [Dataset]. (2021) The Cancer Imaging Archive. DOI: [10.7937/29kw-ae92](https://doi.org/10.7937/29kw-ae92)\n", "\n", "### Publication Citation\n", "Khaled, R., Helal, M., Alfarghaly, O., Mokhtar, O., Elkorany, A., El Kassas, H., & Fahmy, A. Categorized contrast enhanced mammography dataset for diagnostic and artificial intelligence research. (2022) Scientific Data, Volume 9, Issue 1. DOI: [10.1038/s41597-022-01238-0](https://doi.org/10.1038/s41597-022-01238-0)\n", "\n", "### TCIA Citation\n", "Clark K, Vendt B, Smith K, Freymann J, Kirby J, Koppel P, Moore S, Phillips S, Maffitt D, Pringle M, Tarbox L, Prior F. The Cancer Imaging Archive (TCIA): Maintaining and Operating a Public Information Repository, Journal of Digital Imaging, Volume 26, Number 6, December, 2013, pp 1045-1057. DOI: [10.1007/s10278-013-9622-7](https://doi.org/10.1007/s10278-013-9622-7)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10" } }, "nbformat": 4, "nbformat_minor": 5 }