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 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
{
 "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. <b>Categorized Digital Database for Low energy and Subtracted Contrast Enhanced Spectral Mammography images [Dataset].</b> (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. <b>Categorized contrast enhanced mammography dataset for diagnostic and artificial intelligence research.</b> (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. <b>The Cancer Imaging Archive (TCIA): Maintaining and Operating a Public Information Repository</b>, 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
}