<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hannah Do on Medium]]></title>
        <description><![CDATA[Stories by Hannah Do on Medium]]></description>
        <link>https://medium.com/@hannah.hj.do?source=rss-5b0dc3517e74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wb_wax91zAYEVvhXnoFp_A.jpeg</url>
            <title>Stories by Hannah Do on Medium</title>
            <link>https://medium.com/@hannah.hj.do?source=rss-5b0dc3517e74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:13:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hannah.hj.do/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lung Nodule Segmentation (LIDC-IDRI) — Train and Validate]]></title>
            <link>https://medium.com/@hannah.hj.do/lung-nodule-segmentation-lidc-idri-train-and-validate-a30b6ce66ca1?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/a30b6ce66ca1</guid>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[checkpoints]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[lung-nodule]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 08:08:01 GMT</pubDate>
            <atom:updated>2025-09-18T08:14:11.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lung Nodule Segmentation (LIDC-IDRI) — Train and Validate</h3><p>Having prepared the dataset in the <a href="https://medium.com/@hannah.hj.do/lung-nodule-segmentation-lidc-idri-preparing-data-for-inference-6e0667da1c7f">last article</a>, this one will cover <strong>training with U-Net</strong>.</p><h3>U-Net</h3><p>U-Net, introduced in <strong>2015</strong> by Ronneberger, Fischer, and Brox, marked a major breakthrough in biomedical image segmentation. It set the foundation for many later variants, such as 3D U-Net and Attention U-Net.</p><p>Before U-Net, segmentation models often relied on a sliding-window method, where the network analyzed small image patches one at a time. While this worked, it came with long training times and struggled to capture both the overall context and the fine details needed for precise boundaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*8HQ-25ZGRHzwYUh6FVMrRQ.png" /><figcaption>U-Net: Convolutional Networks for Biomedical Image Segmentation (Olaf Ronneberger, Philipp Fischer, and Thomas Brox)</figcaption></figure><p>U-Net solved the challenge by introducing an architecture that resembles the alphabet letter “U.”</p><p>On the left, the <strong>contracting path</strong> compresses the image through layers of convolution and pooling, capturing context and high-level features. On the right, the <strong>expanding path</strong> upsamples those features back to the original resolution, while also pulling in details from the contracting path through <strong>skip connections</strong>.</p><p>This lets the network combine <em>what</em> it sees (context) with <em>where</em> it is (precise location). Because it’s fully convolutional, it avoids redundant patch processing and runs very fast — segmenting a 512×512 image takes less than a second on a GPU.</p><p>To make the model work with very few training images, the authors worked with data augmentation<strong>.</strong> In addition to shifting and rotating images, gray value variations and <em>elastic deformations</em> were applied — stretching and warping images in a smooth, realistic way to mimic how tissues naturally vary between patients. A weighted loss function was also added so the model pays extra attention to border areas where cells touch each other. Training was done with large image tiles, momentum-based optimization, and a pixel-wise softmax loss, which helped the model learn accurate boundaries even with limited data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*GgZSb1TE5RbFaDg6Bi1crw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*jfcmvwE4NW_CTj3IWYJ74A.png" /></figure><p>As a result, U-Net outperformed older models in neuronal and cell segmentation, delivering high accuracy with fewer training samples and training in just ten hours on a Titan GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*u4u54luptORhAJ-oaOXQfQ.png" /></figure><h3>Training U-Net with PyTorch</h3><p>Here I will be providing a walk-through of using U-Net for medical image segmentation — specifically, to identify lung nodules. The malignancy classification step is not considered in this version.</p><p>The code is a customized version from <a href="https://pyimagesearch.com/2021/11/08/u-net-training-image-segmentation-models-in-pytorch/">Shivam Chandhok’s tutorial “U-Net: Training Image Segmentation Models in PyTorch” (PyImageSearch)</a>.</p><p>Required imports :</p><pre>from glob import glob<br>import os<br>import time<br>import torch<br>import cv2<br>import matplotlib.pyplot as plt<br>import torchvision.transforms as T<br>from PIL import Image<br>from torch.nn import ConvTranspose2d, Conv2d, MaxPool2d, Module, ModuleList, ReLU, BCEWithLogitsLoss<br>from torch.nn import functional as F<br>from torch.optim import Adam<br>from torch.utils.data import DataLoader, Dataset<br>from torchvision.transforms import CenterCrop<br>from imutils import paths<br>from tqdm import tqdm</pre><p>Configuration :</p><pre>DATASET_PATH = &quot;lung_nodule_dataset&quot;<br># root folder for train/validation images and masks<br><br>NUM_CHANNELS = 1  <br># Number of channels the model expects, <br># CT slices are typically single-channel (grayscale)<br><br>NUM_CLASSES = 1   <br># Binary segmentation (nodule vs background)<br># BCEWithLogitsLoss, nbClasses=1 is applied -&gt; single logit channel per pixel <br><br>INIT_LR = 0.0001<br># Initial learning rate for Adam<br># modified from 0.001 as the loss plateaued early<br><br>NUM_EPOCHS = 40<br>BATCH_SIZE = 64<br><br>INPUT_IMAGE_WIDTH = 128<br>INPUT_IMAGE_HEIGHT = 128<br># Larger dimensions generally improve results, <br># but kept smaller here to save memory and speed up training.<br><br>THRESHOLD = 0.5<br># Decision cutoff for turning sigmoid probabilities into binary masks<br><br>CHECKPOINT_DIR = &quot;checkpoints&quot;</pre><pre>if torch.backends.mps.is_available():<br>    DEVICE = &quot;mps&quot;<br>elif torch.cuda.is_available():<br>    DEVICE = &quot;cuda&quot;<br>else:<br>    DEVICE = &quot;cpu&quot;<br>PIN_MEMORY = (DEVICE == &quot;cuda&quot;)<br>print(f&quot;[INFO] Using device: {DEVICE}&quot;)<br><br># Device setting <br># mps for apple silicon chips on macOS, then CUDA, else CPU.</pre><p>Segmentation Dataset Class :</p><ul><li>A torch.utils.data.Dataset : loads paired <strong>image</strong> and <strong>mask</strong> files by index, applies transforms to each, returns them as tensor-ready for the model and dataloader.</li></ul><pre>class SegmentationDataset(Dataset):<br>    def __init__(self, imagePaths, maskPaths, image_tfms=None, mask_tfms=None):<br>        assert len(imagePaths) == len(maskPaths), &quot;image/mask count mismatch&quot;<br>        self.imagePaths = imagePaths<br>        self.maskPaths = maskPaths<br>        self.image_tfms = image_tfms <br>        self.mask_tfms = mask_tfms<br>        #  *_tfms : <br>        #  transformation pipelines,<br>        #  preprocesses input images and their segmentation masks <br><br>    def __len__(self):<br>        return len(self.imagePaths)<br><br>    def __getitem__(self, idx):<br>        # Read as grayscale<br>        img = cv2.imread(self.imagePaths[idx], cv2.IMREAD_GRAYSCALE)<br>        mask = cv2.imread(self.maskPaths[idx], cv2.IMREAD_GRAYSCALE)<br><br>        if img is None:<br>            raise FileNotFoundError(f&quot;Image not found: {self.imagePaths[idx]}&quot;)<br>        if mask is None:<br>            raise FileNotFoundError(f&quot;Mask not found: {self.maskPaths[idx]}&quot;)<br><br>        # Convert to PIL for transforms<br>        img_pil = Image.fromarray(img)<br>        mask_pil = Image.fromarray(mask)<br><br>        # Apply transforms &amp; fallback transforms<br>        # fallback resizes and converts to tensor :<br>        #   unsqueeze(0) adds channel for the tensor convention [C, H, W]<br>        #   for grayscale [H, W] -&gt; [1, H, W] <br>        if self.image_tfms is not None:<br>            img_t = self.image_tfms(img_pil)<br>        else:<br>            img_t = torch.from_numpy(img).unsqueeze(0).float() / 255.0<br><br>        if self.mask_tfms is not None:<br>            mask_t = self.mask_tfms(mask_pil)<br>        else:<br>            mask_t = torch.from_numpy(mask).unsqueeze(0).float() / 255.0<br><br>        # Ensure mask is binary - returns 0.0 and 1.0 values only<br>        mask_t = (mask_t &gt;= 0.5).float()<br>        return img_t, mask_t</pre><p>Block, Encoder, Decoder Class :</p><ul><li>Block : Basic building block — two 3x3 convolutions with ReLU activation in between</li></ul><pre>class Block(Module):<br>    def __init__(self, inChannels, outChannels):<br>        super().__init__()<br>        self.conv1 = Conv2d(inChannels, outChannels, 3)<br>        self.relu = ReLU()<br>        self.conv2 = Conv2d(outChannels, outChannels, 3)<br><br>    def forward(self, x):<br>        return self.conv2(self.relu(self.conv1(x)))</pre><ul><li>Encoder : Contracting path that captures context (downsampling)</li></ul><pre>class Encoder(Module):<br>    def __init__(self, channels=(1, 16, 32, 64)):<br>        <br>        super().__init__()<br>        self.encBlocks = ModuleList([<br>            Block(channels[i], channels[i + 1]) <br>            for i in range(len(channels) - 1)<br>        ])<br>        # repeatedly applies a &quot;Block&quot; based on the channel tuple.<br>        # encBlocks = ModuleList([Block(1,16), Block(16,32), Block(32,64)])<br>        #    ModuleList : <br>        #      a torch.nn container that holds PyTorch modules (layers) <br>        #      in a list-like structure <br>        #      + registers as part of the network <br>        #      (only for storing learnable layers that should be tracked)<br>        <br>        # encChannels = (1, 16, 32, 64) meaning the encoder has 3 stages : <br>        #    stage 0 (1-&gt;16), stage 1 (16-&gt;32), stage 2 (32-&gt;64)<br>        <br>        self.pool = MaxPool2d(2)<br>        # 2x2 max-pool with stride 2 that downsamples by 2x after each block<br><br>    def forward(self, x):<br>        blockOutputs = []<br>        for block in self.encBlocks:<br>            x = block(x)<br>            blockOutputs.append(x)<br>            x = self.pool(x)<br>        return blockOutputs<br><br>        # collects the results/tensors of each encoder block (Block + MaxPool)<br>        # - the decoder later needs them for skip connections</pre><ul><li>Decoder : Expanding path that enables precise localization</li></ul><pre>class Decoder(Module):<br>    def __init__(self, channels=(64, 32, 16)):<br>        super().__init__()<br>        self.channels = channels<br>        self.upconvs = ModuleList([<br>            ConvTranspose2d(channels[i], channels[i + 1], 2, 2)<br>            for i in range(len(channels) - 1)<br>        ])<br>        # Tranposed convolution with kernel_size=2, stride=2 (doubles H, W)<br>        # ModuleList([CT(64, 32, 2, 2), CT(32, 16, 2, 2)]) <br><br>        self.decBlocks = ModuleList([<br>            Block(channels[i], channels[i + 1])<br>            for i in range(len(channels) - 1)<br>        ])<br><br>    def forward(self, x, encFeatures):<br>        for i in range(len(self.channels) - 1):<br>            x = self.upconvs[i](x)<br>            # upsample current features <br>            encFeat = self.crop(encFeatures[i], x)<br>            # crop encoder features to match in size<br>            x = torch.cat([x, encFeat], dim=1)<br>            # simply &#39;stacks&#39; encoder features and current upsampled features<br>            x = self.decBlocks[i](x)<br>            # &#39;blends&#39; the combined stack to create slimmer set of feature maps<br>        return x<br><br>    def crop(self, encFeatures, x):<br>        (_, _, H, W) = x.shape<br>        encFeatures = CenterCrop([H, W])(encFeatures)<br>        return encFeatures<br>        # crops encoder features based on the decoder shape<br>        # center crops -&gt; takes off pixels from each side </pre><p>UNet Class (Module)</p><ul><li><strong>U-Net segmentation model</strong> that encodes an input image in to deep features, decodes them with skip connections to restore spatial detail, and produces per-pixel class predictions.</li></ul><pre>class UNet(Module):<br>    def __init__(self, encChannels=(1, 16, 32, 64), decChannels=(64, 32, 16), <br>                 nbClasses=1, retainDim=True, <br>                 outSize=(INPUT_IMAGE_HEIGHT, INPUT_IMAGE_WIDTH)):<br>        super().__init__()<br>        self.encoder = Encoder(encChannels) <br>        # Blocks and MaxPooling layers initialized      <br>        # (1→16), (16→32), (32→64)<br><br>        self.decoder = Decoder(decChannels) <br>        # Upconvs and Block layers initialized <br>        # (64→32), (32→16) <br><br>        self.head = Conv2d(decChannels[-1], nbClasses, 1) <br>        # mapping final feature maps into prediction logits <br>        # = per-pixel classifier<br>        # (16→1)<br><br>        self.retainDim = retainDim<br>        self.outSize = outSize<br><br>    def forward(self, x):<br>        encFeatures = self.encoder(x) <br>        # contract<br>        decFeatures = self.decoder(encFeatures[::-1][0], encFeatures[::-1][1:])<br>        # expand <br>        map = self.head(decFeatures)<br>        # last layer <br>        if self.retainDim:<br>            map = F.interpolate(map, self.outSize)<br>        return map</pre><ul><li>Checkpoint Functions : saves model every 5 epochs and automatically loads recently trained model</li></ul><pre>def find_latest_checkpoint(ckpt_dir):<br>    candidates = sorted(glob(os.path.join(ckpt_dir, &quot;checkpoint_epoch_*.pth&quot;)))<br>    if not candidates:<br>        return None<br>    def epoch_num(path):<br>        try:<br>            return int(os.path.basename(path).split(&quot;_&quot;)[-1].split(&quot;.&quot;)[0])<br>        except:<br>            return -1<br>    return sorted(candidates, key=epoch_num)[-1]<br><br><br>def load_checkpoint(ckpt_path, model, optimizer=None, device=DEVICE):<br>    ckpt = torch.load(ckpt_path, map_location=device)<br>    # Load model state<br>    model.load_state_dict(ckpt.get(&quot;model_state&quot;, ckpt.get(&quot;model_state_dict&quot;, ckpt)))<br>    <br>    # Load optimizer state if provided<br>    if optimizer is not None and (&quot;optimizer_state&quot; in ckpt or &quot;optimizer_state_dict&quot; in ckpt):<br>        optimizer.load_state_dict(ckpt.get(&quot;optimizer_state&quot;, ckpt.get(&quot;optimizer_state_dict&quot;)))<br>        # Move optimizer state to correct device<br>        for state in optimizer.state.values():<br>            for k, v in state.items():<br>                if isinstance(v, torch.Tensor):<br>                    state[k] = v.to(device)<br>                    # to prevent runtime error (mps&lt;-&gt;cpu)<br><br>    # Load training history<br>    hist = {<br>        &quot;train_loss&quot;: ckpt.get(&quot;train_loss&quot;, []),<br>        &quot;val_loss&quot;: ckpt.get(&quot;val_loss&quot;, []),<br>    }<br>    <br>    start_epoch = ckpt.get(&quot;epoch&quot;, 0)<br>    return start_epoch, hist</pre><p>From here on, the pre-defined classes will be used to run the main function.</p><p>if __name__ == “__main__&quot;:</p><ul><li>Data import and transformation</li></ul><pre>    # Dataset paths<br>    TRAIN_IMAGE_PATH = &quot;lung_nodule_dataset/images/train&quot;<br>    TRAIN_MASK_PATH = &quot;lung_nodule_dataset/masks/train&quot;<br>    VAL_IMAGE_PATH = &quot;lung_nodule_dataset/images/val&quot;<br>    VAL_MASK_PATH = &quot;lung_nodule_dataset/masks/val&quot;<br><br>    # Load file paths<br>    trainImages = sorted(list(paths.list_images(TRAIN_IMAGE_PATH)))<br>    trainMasks = sorted(list(paths.list_images(TRAIN_MASK_PATH)))<br>    valImages = sorted(list(paths.list_images(VAL_IMAGE_PATH)))<br>    valMasks = sorted(list(paths.list_images(VAL_MASK_PATH)))<br><br>    print(f&quot;[INFO] found {len(trainImages)} training images and {len(valImages)} validation images&quot;)<br><br>    # Define transforms<br>    image_tfms = T.Compose([<br>        T.Resize((INPUT_IMAGE_HEIGHT, INPUT_IMAGE_WIDTH), interpolation=Image.BILINEAR),<br>            # bilinear interpolation<br>            #   looks at the 4 nearest pixels and takes a weighted average <br>            #   smooth, continuous edges<br>        T.Grayscale(num_output_channels=1),<br>        T.ToTensor(),<br>    ])<br><br>    mask_tfms = T.Compose([<br>        T.Resize((INPUT_IMAGE_HEIGHT, INPUT_IMAGE_WIDTH), interpolation=Image.NEAREST),<br>            # nearest-neighbor interpolation<br>            #   picks the closest pixel (no averaging)<br>            #   sharp, blocky edges <br>            #   each pixel is a class label (has to be 0 or 1) <br>        T.Grayscale(num_output_channels=1),<br>        T.ToTensor(),<br>    ])<br><br>    # Create datasets and data loaders<br>    trainDS = SegmentationDataset(trainImages, trainMasks, image_tfms, mask_tfms)<br>    valDS = SegmentationDataset(valImages, valMasks, image_tfms, mask_tfms)<br><br>    trainLoader = DataLoader(trainDS, shuffle=True, batch_size=BATCH_SIZE, pin_memory=PIN_MEMORY)<br>    valLoader = DataLoader(valDS, shuffle=False, batch_size=BATCH_SIZE, pin_memory=PIN_MEMORY)<br><br>    trainSteps = len(trainLoader)<br>    valSteps = len(valLoader)<br><br>    print(f&quot;[INFO] found {len(trainDS)} examples in training set and {len(valDS)} examples in validation set&quot;)</pre><ul><li>Model, loss, and optimizer initialization</li></ul><pre>    # Initialize model, loss, and optimizer<br>    unet = UNet(encChannels=(1, 16, 32, 64)).to(DEVICE)<br>    lossFunc = BCEWithLogitsLoss()<br>    opt = Adam(unet.parameters(), lr=INIT_LR)<br><br>    # Initialize training history<br>    H = {&quot;train_loss&quot;: [], &quot;val_loss&quot;: []}<br><br>    # Try to resume from checkpoint<br>    os.makedirs(CHECKPOINT_DIR, exist_ok=True)<br>    latest = find_latest_checkpoint(CHECKPOINT_DIR)<br>    start_epoch = 0<br>    <br>    if latest is not None:<br>        start_epoch, hist = load_checkpoint(latest, unet, opt, DEVICE)<br>        H[&quot;train_loss&quot;] = hist.get(&quot;train_loss&quot;, [])<br>        H[&quot;val_loss&quot;] = hist.get(&quot;val_loss&quot;, [])<br>        print(f&quot;[INFO] Resuming from checkpoint: {latest} (start at epoch {start_epoch+1})&quot;)<br>    else:<br>        print(&quot;[INFO] No checkpoint found, starting fresh.&quot;)</pre><ul><li>Training loop</li></ul><pre>    print(&quot;[INFO] training the network...&quot;)<br>    startTime = time.time()<br><br>    for e in tqdm(range(start_epoch, NUM_EPOCHS), initial=start_epoch, total=NUM_EPOCHS, desc=&quot;epochs&quot;):<br>        # Training phase<br>        unet.train()<br>        totalTrainLoss = 0.0<br>        for i, (x, y) in enumerate(trainLoader):<br>            x, y = x.to(DEVICE), y.to(DEVICE)   # moves tensors to mps/gpu/cpu<br>            # x: Input images (batch_size × 1 × 128 × 128)<br>            # y: Ground truth masks (batch_size × 1 × 128 × 128) <br>            pred = unet(x)   # forward pass <br>            loss = lossFunc(pred, y)   # loss calculation <br><br>            # pytorch training iteration recipe <br>            opt.zero_grad()    # clears gradients from previous iteration<br>            loss.backward()    # computes gradients via backpropagation<br>            opt.step()         # updates model parameters using Adam optimizer<br>                               #   based on computed gradients <br><br>            totalTrainLoss += loss.item()<br><br>        # Validation phase<br>        unet.eval()   # sets model to evaluation mode <br>        totalValLoss = 0.0<br>        with torch.no_grad():    # disables gradient computation <br>                                 # prevents accidental parameter updates<br>            for x, y in valLoader:<br>                x, y = x.to(DEVICE), y.to(DEVICE)<br>                pred = unet(x)<br>                vloss = lossFunc(pred, y)<br>                totalValLoss += vloss.item()<br><br>        # Calculate averages and log<br>        avgTrainLoss = totalTrainLoss / trainSteps<br>        avgValLoss = totalValLoss / valSteps<br><br>        H[&quot;train_loss&quot;].append(avgTrainLoss)<br>        H[&quot;val_loss&quot;].append(avgValLoss)<br><br>        print(f&quot;[INFO] EPOCH {e+1}/{NUM_EPOCHS} | Train {avgTrainLoss:.6f} | Val {avgValLoss:.6f}&quot;)<br><br>        # Save checkpoint every 5 epochs<br>        if (e + 1) % 5 == 0:<br>            ckpt_path = os.path.join(CHECKPOINT_DIR, f&quot;checkpoint_epoch_{e+1}.pth&quot;)<br>            torch.save({<br>                &quot;epoch&quot;: e + 1,<br>                &quot;model_state&quot;: unet.state_dict(),<br>                &quot;optimizer_state&quot;: opt.state_dict(),<br>                &quot;train_loss&quot;: H[&quot;train_loss&quot;],<br>                &quot;val_loss&quot;: H[&quot;val_loss&quot;],<br>            }, ckpt_path)<br>            print(f&quot;[INFO] Saved checkpoint: {ckpt_path}&quot;)<br><br>    endTime = time.time()</pre><p>Running the code will provide following logs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*yeEV-T16ZKZE-eIt5-2skA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*nJdj77aJRAOk8ZWLNR5r2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*2icHRQCdycQ9fBMI0_0IEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*PK3OM0qkAE2uWC-qP56H8A.png" /></figure><p>The total training time took about 6–7 hours and following is the change of training and validation loss :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*gNdjkO0H98yKCBGyGw9V9Q.png" /></figure><p>However… a low BCE loss doesn’t necessarily mean good segmentation performance. Next article will deal with IoU/Dice curves with alternative loss functions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9Pk6tjP4BNXmxkOJE7%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbrooklynninenine-nbc-tv-show-brooklyn99-9Pk6tjP4BNXmxkOJE7&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExd3FzbjdpamM0dHJvN2pnaHZ6Z3lna2QyaG50OGZyY3JndTgyMTZzZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F9Pk6tjP4BNXmxkOJE7%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/d629d9d275468126a803a16575cec6ca/href">https://medium.com/media/d629d9d275468126a803a16575cec6ca/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a30b6ce66ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lung Nodule Segmentation (LIDC-IDRI) — Preparing Data for Inference]]></title>
            <link>https://medium.com/@hannah.hj.do/lung-nodule-segmentation-lidc-idri-preparing-data-for-inference-6e0667da1c7f?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0667da1c7f</guid>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 02:59:51 GMT</pubDate>
            <atom:updated>2025-09-23T00:36:56.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lung Nodule Segmentation (LIDC-IDRI) — Preparing Data for Inference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*UwTvDL_xmbGItXEa1PcUKw.png" /></figure><p>Using the lung CT scans and manual segmentations of pulmonary nodules provided by radiologists, we can prepare the dataset for training a segmentation model.</p><p>The <a href="https://www.cancerimagingarchive.net/collection/lidc-idri/"><strong>LIDC-IDRI dataset</strong></a> is a large collaborative effort between seven academic centers and eight medical imaging companies, comprising <strong>1,018 cases</strong>. Each case includes thoracic CT images and an accompanying XML file that documents a two-stage annotation process by four experienced thoracic radiologists:</p><ul><li><strong>Blinded read:</strong> Each radiologist independently reviewed every CT scan and categorized lesions into one of three groups: <em>nodule ≥ 3 mm</em>, <em>nodule ≤ 3 mm</em>, and <em>non-nodule ≥ 3 mm</em>.</li><li><strong>Unblinded read:</strong> Each radiologist then revisited their annotations while viewing the anonymized markings of the other three, providing a final judgment.</li></ul><p>This approach aimed to comprehensively identify all nodules in each scan without enforcing consensus among the readers.</p><p>The dataset distributes CT images in the <strong>DICOM</strong> format, and annotations provided in <strong>XML</strong>, typically processed with the <em>pylidc</em> library. However, due to version compatibility issues, I decided to parse and visualize the XML annotations without the library — then convert the files into a PyTorch-ready format.</p><p>DICOM and XML data last updated in 2020/09/21 were downloaded from the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol-_CX0hCDJpSyublHdtWQ.png" /><figcaption><a href="https://www.cancerimagingarchive.net/collection/lidc-idri/">https://www.cancerimagingarchive.net/collection/lidc-idri/</a></figcaption></figure><p>The annotated XML file structure is divided into multiple sections.</p><ul><li>Response Header : Metadata for the reading session — includes datetime, series and study UIDs, description and comments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*9GKtIPAAP1mP9eIg6OIvnA.png" /><figcaption>Response Header</figcaption></figure><ul><li>Reading Session : Details of the annotation on lung nodules such as the noduleID, characteristics of the nodule (margin, malignancy), ROI (regions of interest — edgeMap around a lung nodule) for each CT slice, image SOP UID, Z-position, and etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*68PEJ2hjBp1L_iDHC2sCkw.png" /><figcaption>Reading Session</figcaption></figure><p>Nodules and<strong> non-nodules</strong> were annotated as the non-nodules initially resemble nodules however turn out to be false positives. In this sample model training I will initially focus on nodules only, with a portion of the DICOM data.</p><h3>Visualizing DICOM and XML (Annotation) Data</h3><p>Following is the code used to pre-process XML data and to visualize with the DICOM image.</p><pre>import pydicom<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from matplotlib.patches import Polygon<br>import cv2<br>from pathlib import Path<br>import xml.etree.ElementTree as ET<br><br><br>class DICOMVisualizerWithMalignancy:<br>    def __init__(self):<br>        self.dicom_data = {}<br>        self.annotations = {}<br>        <br>    def load_dicom_series(self, dicom_folder):<br>        &quot;&quot;&quot;Load DICOM series from folder&quot;&quot;&quot;<br>        dicom_files = []<br>        for file_path in Path(dicom_folder).glob(&quot;*.dcm&quot;):<br>            try:<br>                ds = pydicom.dcmread(file_path)<br>                dicom_files.append((ds.SOPInstanceUID, ds))<br>            except Exception as e:<br>                print(f&quot;Error reading {file_path}: {e}&quot;)<br>        <br>        # Sort by instance number if available<br>        try:<br>            dicom_files.sort(key=lambda x: int(x[1].InstanceNumber))<br>        except:<br>            pass<br>            <br>        self.dicom_data = {sop_id: ds for sop_id, ds in dicom_files}<br>        print(f&quot;Loaded {len(self.dicom_data)} DICOM files&quot;)<br>        return self.dicom_data<br>    <br>    def parse_lidc_xml(self, xml_path):<br>        &quot;&quot;&quot;Parse LIDC XML file and return nodules data&quot;&quot;&quot;<br>        ns = {&#39;lidc&#39;: &#39;http://www.nih.gov&#39;}<br>        root = ET.parse(xml_path).getroot()<br><br>        def txt(elem, tag):<br>            t = elem.find(f&#39;lidc:{tag}&#39;, ns)<br>            return t.text.strip() if t is not None and t.text is not None else None<br><br>        nodules = []<br>        for session in root.findall(&#39;lidc:readingSession&#39;, ns):<br>            for n in session.findall(&#39;lidc:unblindedReadNodule&#39;, ns):<br>                nid = txt(n, &#39;noduleID&#39;)<br>                c = n.find(&#39;lidc:characteristics&#39;, ns)<br>                characteristics = {}<br>                if c is not None:<br>                    characteristics = {<br>                        &#39;malignancy&#39;: txt(c, &#39;malignancy&#39;),<br>                        &#39;spiculation&#39;: txt(c, &#39;spiculation&#39;),<br>                        &#39;sphericity&#39;: txt(c, &#39;sphericity&#39;),<br>                        &#39;margin&#39;: txt(c, &#39;margin&#39;),<br>                        &#39;calcification&#39;: txt(c, &#39;calcification&#39;)<br>                    }<br><br>                rois = []<br>                for roi in n.findall(&#39;lidc:roi&#39;, ns):<br>                    z = txt(roi, &#39;imageZposition&#39;)<br>                    sop = txt(roi, &#39;imageSOP_UID&#39;) or txt(roi, &#39;imageSOP_UID &#39;)<br>                    inc = txt(roi, &#39;inclusion&#39;)<br>                    pts = []<br>                    for em in roi.findall(&#39;lidc:edgeMap&#39;, ns):<br>                        x = int(em.find(&#39;lidc:xCoord&#39;, ns).text)<br>                        y = int(em.find(&#39;lidc:yCoord&#39;, ns).text)<br>                        pts.append((x, y))<br>                    <br>                    rois.append({<br>                        &#39;z&#39;: float(z) if z is not None else None,<br>                        &#39;sop&#39;: sop,<br>                        &#39;inclusion&#39;: (inc == &#39;TRUE&#39;),<br>                        &#39;points&#39;: pts<br>                    })<br><br>                nodules.append({<br>                    &#39;noduleID&#39;: nid,<br>                    &#39;rois&#39;: rois,<br>                    &#39;characteristics&#39;: characteristics<br>                })<br>        return nodules<br>    <br>    def parse_annotations(self, nodules_data):<br>        &quot;&quot;&quot;Parse LIDC annotation data into organized structure&quot;&quot;&quot;<br>        self.annotations = {}<br>        <br>        for nodule in nodules_data:<br>            nodule_id = nodule[&#39;noduleID&#39;]<br>            characteristics = nodule.get(&#39;characteristics&#39;, {})<br>            <br>            for roi in nodule[&#39;rois&#39;]:<br>                sop_id = roi[&#39;sop&#39;]<br>                z_coord = roi[&#39;z&#39;]<br>                points = roi[&#39;points&#39;]<br>                inclusion = roi.get(&#39;inclusion&#39;, True)<br>                <br>                if sop_id not in self.annotations:<br>                    self.annotations[sop_id] = {&#39;nodules&#39;: [], &#39;characteristics&#39;: {}}<br>                <br>                self.annotations[sop_id][&#39;nodules&#39;].append({<br>                    &#39;id&#39;: nodule_id,<br>                    &#39;points&#39;: points,<br>                    &#39;z&#39;: z_coord,<br>                    &#39;inclusion&#39;: inclusion,<br>                    &#39;characteristics&#39;: characteristics<br>                })<br>                <br>                # Store characteristics at slice level<br>                if not self.annotations[sop_id][&#39;characteristics&#39;]:<br>                    self.annotations[sop_id][&#39;characteristics&#39;] = characteristics<br>    <br>    def get_malignancy_color(self, malignancy_score):<br>        &quot;&quot;&quot;Get color based on malignancy score&quot;&quot;&quot;<br>        if not malignancy_score:<br>            return &#39;gray&#39;, &#39;white&#39;<br>            <br>        try:<br>            score = int(malignancy_score)<br>            if score &lt;= 2:<br>                return &#39;green&#39;, &#39;white&#39;  # Low malignancy<br>            elif score == 3:<br>                return &#39;orange&#39;, &#39;black&#39;  # Moderate malignancy<br>            else:  # score &gt;= 4<br>                return &#39;red&#39;, &#39;white&#39;  # High malignancy<br>        except:<br>            return &#39;gray&#39;, &#39;white&#39;<br>    <br>    def visualize_slice(self, sop_id, figsize=(15, 8)):<br>        &quot;&quot;&quot;Visualize a single DICOM slice with annotations and malignancy info&quot;&quot;&quot;<br>        if sop_id not in self.dicom_data:<br>            print(f&quot;DICOM with SOP ID {sop_id} not found&quot;)<br>            return None<br>            <br>        # Get DICOM data<br>        ds = self.dicom_data[sop_id]<br>        image = ds.pixel_array.astype(float)<br>        <br>        # Apply windowing if available<br>        if hasattr(ds, &#39;WindowCenter&#39;) and hasattr(ds, &#39;WindowWidth&#39;):<br>            wc = ds.WindowCenter<br>            ww = ds.WindowWidth<br>            if isinstance(wc, list):<br>                wc, ww = wc[0], ww[0]<br>            image = np.clip((image - wc + ww/2) / ww * 255, 0, 255)<br>        else:<br>            # Basic normalization<br>            image = ((image - image.min()) / (image.max() - image.min()) * 255)<br>        <br>        # Create visualization<br>        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=figsize)<br>        annotations = self.annotations.get(sop_id, {&#39;nodules&#39;: [], &#39;characteristics&#39;: {}})<br><br>        # Display original image with annotations<br>        ax1.imshow(image, cmap=&#39;gray&#39;)<br>        ax1.set_title(f&#39;DICOM Slice with Malignancy Labels\nSOP: {sop_id[:20]}...&#39;)<br>        ax1.axis(&#39;off&#39;)<br>        <br>        # Create masks<br>        nodule_mask = np.zeros(image.shape, dtype=np.uint8)<br>        <br>        # Group nodules by ID to handle multiple annotations<br>        nodule_groups = {}<br>        for nodule in annotations[&#39;nodules&#39;]:<br>            nid = nodule[&#39;id&#39;]<br>            if nid not in nodule_groups:<br>                nodule_groups[nid] = []<br>            nodule_groups[nid].append(nodule)<br>        <br>        # Collect all nodule positions for better label placement<br>        all_nodule_bounds = []<br>        for nodule_list in nodule_groups.values():<br>            for nodule in nodule_list:<br>                if len(nodule[&#39;points&#39;]) &gt;= 3:<br>                    x_coords = [p[0] for p in nodule[&#39;points&#39;]]<br>                    y_coords = [p[1] for p in nodule[&#39;points&#39;]]<br>                    all_nodule_bounds.append({<br>                        &#39;min_x&#39;: min(x_coords), &#39;max_x&#39;: max(x_coords),<br>                        &#39;min_y&#39;: min(y_coords), &#39;max_y&#39;: max(y_coords),<br>                        &#39;centroid_x&#39;: np.mean(x_coords), &#39;centroid_y&#39;: np.mean(y_coords)<br>                    })<br>        <br>        # Keep track of used label positions with more precise collision detection<br>        used_labels = []  # Store (x, y, width, height) for each label<br>        <br>        def find_best_label_position(nodule_bounds, label_text, attempt=0):<br>            &quot;&quot;&quot;Find the best position for a label that doesn&#39;t overlap with others&quot;&quot;&quot;<br>            centroid_x = nodule_bounds[&#39;centroid_x&#39;]<br>            centroid_y = nodule_bounds[&#39;centroid_y&#39;]<br>            min_x, max_x = nodule_bounds[&#39;min_x&#39;], nodule_bounds[&#39;max_x&#39;]<br>            min_y, max_y = nodule_bounds[&#39;min_y&#39;], nodule_bounds[&#39;max_y&#39;]<br>            <br>            # Estimate label size (rough approximation)<br>            label_width = len(label_text.split(&#39;\n&#39;)[0]) * 8 + 20<br>            label_height = len(label_text.split(&#39;\n&#39;)) * 12 + 10<br>            <br>            # Define candidate positions with increasing distance<br>            base_offset = 40 + (attempt * 20)  # Start farther away, increase more with each attempt<br>            <br>            candidates = [<br>                # Primary positions - farther from nodule edges<br>                (max_x + base_offset, centroid_y, &#39;right&#39;),<br>                (min_x - base_offset, centroid_y, &#39;left&#39;),<br>                (centroid_x, min_y - base_offset, &#39;top&#39;),<br>                (centroid_x, max_y + base_offset, &#39;bottom&#39;),<br>                <br>                # Corner positions<br>                (max_x + base_offset, min_y, &#39;top-right&#39;),<br>                (max_x + base_offset, max_y, &#39;bottom-right&#39;),<br>                (min_x - base_offset, min_y, &#39;top-left&#39;),<br>                (min_x - base_offset, max_y, &#39;bottom-left&#39;),<br>                <br>                # Extended positions<br>                (centroid_x + base_offset, min_y - base_offset, &#39;top-right-ext&#39;),<br>                (centroid_x - base_offset, min_y - base_offset, &#39;top-left-ext&#39;),<br>                (centroid_x + base_offset, max_y + base_offset, &#39;bottom-right-ext&#39;),<br>                (centroid_x - base_offset, max_y + base_offset, &#39;bottom-left-ext&#39;),<br>            ]<br>            <br>            for x, y, pos_type in candidates:<br>                # Check bounds - ensure label stays well within image<br>                if (x &lt; label_width/2 + 10 or y &lt; label_height/2 + 10 or <br>                    x &gt; image.shape[1] - label_width/2 - 10 or y &gt; image.shape[0] - label_height/2 - 10):<br>                    continue<br>                    <br>                # Check collision with existing labels<br>                collision = False<br>                for used_x, used_y, used_w, used_h in used_labels:<br>                    if (abs(x - used_x) &lt; (label_width + used_w) / 2 + 15 and <br>                        abs(y - used_y) &lt; (label_height + used_h) / 2 + 15):<br>                        collision = True<br>                        break<br>                <br>                # CRITICAL: Check if label would overlap with ANY nodule area (including its own)<br>                nodule_collision = False<br>                for bounds in all_nodule_bounds:<br>                    # Create expanded boundary around nodule (safety margin)<br>                    nodule_margin = 15<br>                    expanded_min_x = bounds[&#39;min_x&#39;] - nodule_margin<br>                    expanded_max_x = bounds[&#39;max_x&#39;] + nodule_margin  <br>                    expanded_min_y = bounds[&#39;min_y&#39;] - nodule_margin<br>                    expanded_max_y = bounds[&#39;max_y&#39;] + nodule_margin<br>                    <br>                    # Check if label bounding box overlaps with expanded nodule area<br>                    label_min_x = x - label_width/2<br>                    label_max_x = x + label_width/2<br>                    label_min_y = y - label_height/2<br>                    label_max_y = y + label_height/2<br>                    <br>                    if (label_max_x &gt; expanded_min_x and label_min_x &lt; expanded_max_x and<br>                        label_max_y &gt; expanded_min_y and label_min_y &lt; expanded_max_y):<br>                        nodule_collision = True<br>                        break<br>                <br>                if not collision and not nodule_collision:<br>                    return x, y, label_width, label_height<br>            <br>            # If no good position found, try with increased offset<br>            if attempt &lt; 4:  # Try more attempts<br>                return find_best_label_position(nodule_bounds, label_text, attempt + 1)<br>            <br>            # Fallback: place it far right with vertical stacking, well clear of nodules<br>            max_nodule_x = max(all_nodule_bounds, key=lambda b: b[&#39;max_x&#39;])[&#39;max_x&#39;]<br>            fallback_x = max_nodule_x + 100 + (attempt * 25)  # Much farther right<br>            fallback_y = 60 + len(used_labels) * 35  # More vertical spacing<br>            return fallback_x, fallback_y, label_width, label_height<br>        <br>        # Plot nodule annotations with advanced positioning<br>        for nodule_id, nodule_list in nodule_groups.items():<br>            for j, nodule in enumerate(nodule_list):<br>                points = nodule[&#39;points&#39;]<br>                if len(points) &gt;= 3:<br>                    # Get malignancy info<br>                    characteristics = nodule.get(&#39;characteristics&#39;, {})<br>                    malignancy = characteristics.get(&#39;malignancy&#39;)<br>                    <br>                    # Get malignancy-based colors<br>                    bbox_color, text_color = self.get_malignancy_color(malignancy)<br>                    <br>                    # Create polygon with malignancy-based edge color<br>                    edge_color = bbox_color if malignancy else (&#39;red&#39; if nodule[&#39;inclusion&#39;] else &#39;blue&#39;)<br>                    poly = Polygon(points, closed=True, alpha=0.15,<br>                                 facecolor=&#39;none&#39;,  <br>                                 edgecolor=edge_color,<br>                                 linewidth=2)<br>                    ax1.add_patch(poly)<br>                    <br>                    # Calculate nodule boundaries<br>                    x_coords = [p[0] for p in points]<br>                    y_coords = [p[1] for p in points]<br>                    nodule_bounds = {<br>                        &#39;min_x&#39;: min(x_coords), &#39;max_x&#39;: max(x_coords),<br>                        &#39;min_y&#39;: min(y_coords), &#39;max_y&#39;: max(y_coords),<br>                        &#39;centroid_x&#39;: np.mean(x_coords), &#39;centroid_y&#39;: np.mean(y_coords)<br>                    }<br>                    <br>                    # Create label text<br>                    if len(nodule_list) &gt; 1:<br>                        label_text = f&quot;N{nodule_id}-R{j+1}&quot;<br>                        if malignancy:<br>                            label_text += f&quot;\nM:{malignancy}&quot;<br>                    else:<br>                        label_text = f&quot;N{nodule_id}&quot;<br>                        if malignancy:<br>                            label_text += f&quot;\nM:{malignancy}&quot;<br>                    <br>                    # Find best position for this label<br>                    label_x, label_y, label_w, label_h = find_best_label_position(nodule_bounds, label_text)<br>                    used_labels.append((label_x, label_y, label_w, label_h))<br>                    <br>                    # Draw connecting line from nodule to label<br>                    ax1.plot([nodule_bounds[&#39;centroid_x&#39;], label_x], [nodule_bounds[&#39;centroid_y&#39;], label_y], <br>                            color=bbox_color, linewidth=1, alpha=0.6, linestyle=&#39;--&#39;)<br>                    <br>                    # Place label at calculated position<br>                    ax1.text(label_x, label_y, label_text, <br>                            color=text_color, fontsize=8, ha=&#39;center&#39;, va=&#39;center&#39;, weight=&#39;bold&#39;,<br>                            bbox=dict(boxstyle=&#39;round,pad=0.2&#39;, facecolor=bbox_color, <br>                                    alpha=0.9, edgecolor=&#39;black&#39;, linewidth=1))<br>                    <br>                    # Create mask for inclusion nodules<br>                    if nodule[&#39;inclusion&#39;] and len(points) &gt;= 3:<br>                        pts = np.array(points, dtype=np.int32)<br>                        cv2.fillPoly(nodule_mask, [pts], 255)<br>        <br>        # Create legend<br>        if annotations[&#39;nodules&#39;]:<br>            legend_elements = [<br>                plt.Line2D([0], [0], marker=&#39;s&#39;, color=&#39;w&#39;, markerfacecolor=&#39;green&#39;, <br>                          markersize=10, alpha=0.9, label=&#39;Low Malignancy (1-2)&#39;, markeredgecolor=&#39;black&#39;),<br>                plt.Line2D([0], [0], marker=&#39;s&#39;, color=&#39;w&#39;, markerfacecolor=&#39;orange&#39;, <br>                          markersize=10, alpha=0.9, label=&#39;Moderate Malignancy (3)&#39;, markeredgecolor=&#39;black&#39;),<br>                plt.Line2D([0], [0], marker=&#39;s&#39;, color=&#39;w&#39;, markerfacecolor=&#39;red&#39;, <br>                          markersize=10, alpha=0.9, label=&#39;High Malignancy (4-5)&#39;, markeredgecolor=&#39;black&#39;),<br>                plt.Line2D([0], [0], marker=&#39;s&#39;, color=&#39;w&#39;, markerfacecolor=&#39;gray&#39;, <br>                          markersize=10, alpha=0.9, label=&#39;No Malignancy Data&#39;, markeredgecolor=&#39;black&#39;)<br>            ]<br>            ax1.legend(handles=legend_elements, loc=&#39;upper left&#39;, fontsize=9, framealpha=0.9)<br>        <br>        # Display nodule mask<br>        ax2.imshow(nodule_mask, cmap=&#39;hot&#39;)<br>        ax2.set_title(&#39;Inclusion Masks Only&#39;)<br>        ax2.axis(&#39;off&#39;)<br>        <br>        # Display overlay<br>        ax3.imshow(image, cmap=&#39;gray&#39;)<br>        ax3.imshow(nodule_mask, cmap=&#39;hot&#39;, alpha=0.4)<br>        ax3.set_title(&#39;Overlay (Inclusion Only)&#39;)<br>        ax3.axis(&#39;off&#39;)<br>        <br>        plt.tight_layout()<br>        return fig, nodule_mask<br>    <br>    def get_slice_with_annotations(self, max_slices=10):<br>        &quot;&quot;&quot;Get SOP IDs of slices that have annotations&quot;&quot;&quot;<br>        annotated_slices = []<br>        for sop_id, annotations in self.annotations.items():<br>            if annotations[&#39;nodules&#39;]:<br>                annotated_slices.append(sop_id)<br>                if len(annotated_slices) &gt;= max_slices:<br>                    break<br>        return annotated_slices<br><br><br># Example usage<br>def main():<br>    # Initialize visualizer<br>    visualizer = DICOMVisualizerWithMalignancy()<br>    <br>    # Parse XML annotations<br>    xml_path = &quot;&quot; # path to your xml file<br>    annotations = visualizer.parse_lidc_xml(xml_path)<br>    <br>    # Load DICOM data<br>    dicom_folder = &quot;&quot; # path to your dicom file folder <br>    visualizer.load_dicom_series(dicom_folder)<br>    <br>    # Parse annotations<br>    visualizer.parse_annotations(annotations)<br>    <br>    # Find and visualize annotated slices<br>    annotated_slices = visualizer.get_slice_with_annotations()<br>    print(f&quot;Found {len(annotated_slices)} slices with annotations&quot;)<br>    <br>    # Visualize first few slices<br>    for i, sop_id in enumerate(annotated_slices[:3]):<br>        if sop_id in visualizer.dicom_data:<br>            print(f&quot;Visualizing slice {i+1}: {sop_id}&quot;)<br>            fig, mask = visualizer.visualize_slice(sop_id)<br>            plt.show()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>As a result, the axial DICOM slices of a single subject across different Z positions were visualized, along with annotated regions of interest (ROIs) and malignancy ratings provided from up to 4 radiologists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yFhfPpbX7hx6nUoDzeoNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCt_hEsV_CQvSmisL2npWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPxSVDfp5pt4G6mVVhGRqA.png" /></figure><h3>Turning DICOM + XML into train/val/test data for PyTorch</h3><p>Next step is to transform the data into a trainable format by PyTorch.</p><p>Following code…</p><ol><li>matches Image SOP UID from XML file with the UID in DICOM files,</li><li>splits the data into train, validation, and test data,</li><li>creates images and masks in numpy and png formats,</li><li>and stores metadata for the dataset.</li></ol><pre>import pydicom<br>import numpy as np<br>import cv2<br>from pathlib import Path<br>import xml.etree.ElementTree as ET<br>from PIL import Image<br>import json<br>from sklearn.model_selection import train_test_split<br><br>class DICOMToTrainingDataConverter:<br>    def __init__(self, output_base_dir=&quot;training_data&quot;):<br>        self.output_base_dir = Path(output_base_dir)<br>        self.dicom_data = {}<br>        self.annotations = {}<br>        <br>        # Create directory structure<br>        self.setup_directories()<br>        <br>    def setup_directories(self):<br>        &quot;&quot;&quot;Create organized directory structure for training data&quot;&quot;&quot;<br>        dirs_to_create = [<br>            self.output_base_dir / &quot;images&quot; / &quot;train&quot;,<br>            self.output_base_dir / &quot;images&quot; / &quot;val&quot;, <br>            self.output_base_dir / &quot;images&quot; / &quot;test&quot;,<br>            self.output_base_dir / &quot;masks&quot; / &quot;train&quot;,<br>            self.output_base_dir / &quot;masks&quot; / &quot;val&quot;,<br>            self.output_base_dir / &quot;masks&quot; / &quot;test&quot;,<br>            self.output_base_dir / &quot;metadata&quot;,<br>        ]<br>        <br>        for dir_path in dirs_to_create:<br>            dir_path.mkdir(parents=True, exist_ok=True)<br>            <br>        print(f&quot;Created directory structure at: {self.output_base_dir}&quot;)<br>    <br>    def load_dicom_series(self, dicom_folder):<br>        &quot;&quot;&quot;Load DICOM series from folder&quot;&quot;&quot;<br>        dicom_files = []<br>        for file_path in Path(dicom_folder).glob(&quot;*.dcm&quot;):<br>            try:<br>                ds = pydicom.dcmread(file_path)<br>                dicom_files.append((ds.SOPInstanceUID, ds))<br>            except Exception as e:<br>                print(f&quot;Error reading {file_path}: {e}&quot;)<br>        <br>        # Sort by instance number if available<br>        try:<br>            dicom_files.sort(key=lambda x: int(x[1].InstanceNumber))<br>        except:<br>            pass<br>            <br>        self.dicom_data = {sop_id: ds for sop_id, ds in dicom_files}<br>        print(f&quot;Loaded {len(self.dicom_data)} DICOM files&quot;)<br>        return self.dicom_data<br>    <br>    def parse_annotations(self, nodules_data):<br>        &quot;&quot;&quot;Parse LIDC annotation data into organized structure&quot;&quot;&quot;<br>        self.annotations = {}<br>        <br>        for nodule in nodules_data:<br>            nodule_id = nodule[&#39;noduleID&#39;]<br>            characteristics = nodule.get(&#39;characteristics&#39;, {})<br>            <br>            for roi in nodule[&#39;rois&#39;]:<br>                sop_id = roi[&#39;sop&#39;]<br>                z_coord = roi[&#39;z&#39;]<br>                points = roi[&#39;points&#39;]<br>                inclusion = roi.get(&#39;inclusion&#39;, True)<br>                <br>                if sop_id not in self.annotations:<br>                    self.annotations[sop_id] = {&#39;nodules&#39;: [], &#39;characteristics&#39;: {}}<br>                <br>                self.annotations[sop_id][&#39;nodules&#39;].append({<br>                    &#39;id&#39;: nodule_id,<br>                    &#39;points&#39;: points,<br>                    &#39;z&#39;: z_coord,<br>                    &#39;inclusion&#39;: inclusion,<br>                    &#39;type&#39;: &#39;nodule&#39;,<br>                    &#39;characteristics&#39;: characteristics<br>                })<br>                <br>                if not self.annotations[sop_id][&#39;characteristics&#39;]:<br>                    self.annotations[sop_id][&#39;characteristics&#39;] = characteristics<br>    <br>    def create_mask_from_points(self, points, image_shape):<br>        &quot;&quot;&quot;Create binary mask from polygon points&quot;&quot;&quot;<br>        if points is None or len(points) &lt; 3:<br>            return np.zeros(image_shape, dtype=np.uint8)<br>        <br>        pts = np.asarray(points, dtype=np.int32).reshape(-1, 1, 2)<br>        mask = np.zeros(image_shape, dtype=np.uint8)<br>        cv2.fillPoly(mask, [pts], 255)<br>        return mask<br>    <br>    def preprocess_dicom_image(self, ds, normalize_method=&#39;minmax&#39;):<br>        &quot;&quot;&quot;Preprocess DICOM image for training&quot;&quot;&quot;<br>        # Convert to float32<br>        image = ds.pixel_array.astype(np.float32)<br><br>        # Convert to Hounsfield Units if rescale is present<br>        slope = float(getattr(ds, &#39;RescaleSlope&#39;, 1.0) or 1.0)<br>        intercept = float(getattr(ds, &#39;RescaleIntercept&#39;, 0.0) or 0.0)<br>        image = image * slope + intercept<br><br>        # Helper function to handle MultiValue parameters<br>        def _first_scalar(v, default=None):<br>            if v is None:<br>                return default<br>            try:<br>                if hasattr(v, &#39;__iter__&#39;) and not isinstance(v, (str, bytes)):<br>                    return float(v[0])<br>                return float(v)<br>            except Exception:<br>                return default<br><br>        wc = _first_scalar(getattr(ds, &#39;WindowCenter&#39;, None))<br>        ww = _first_scalar(getattr(ds, &#39;WindowWidth&#39;, None))<br><br>        # Apply windowing based on method<br>        if normalize_method == &#39;hu_window&#39;:<br>            # Standard lung window<br>            lo, hi = -1000.0, 400.0<br>            img = np.clip(image, lo, hi)<br>            img = (img - lo) / (hi - lo) * 255.0<br>            return img.astype(np.float32)<br><br>        # Use DICOM window center/width if available<br>        if wc is not None and ww is not None and ww &gt; 1e-6:<br>            lo = wc - ww / 2.0<br>            hi = wc + ww / 2.0<br>            img = np.clip(image, lo, hi)<br>            img = (img - lo) / (hi - lo) * 255.0<br>            return img.astype(np.float32)<br><br>        # Fallback normalization methods<br>        if normalize_method == &#39;zscore&#39;:<br>            sd = image.std()<br>            sd = sd if sd &gt; 1e-6 else 1.0<br>            img = (image - image.mean()) / sd<br>            rng = img.max() - img.min()<br>            img = (img - img.min()) / (rng + 1e-6) * 255.0<br>            return img.astype(np.float32)<br><br>        # Default minmax normalization<br>        rng = image.max() - image.min()<br>        img = (image - image.min()) / (rng + 1e-6) * 255.0<br>        return img.astype(np.float32)<br>    <br>    def extract_slice_data(self, sop_id, normalize_method=&#39;minmax&#39;):<br>        &quot;&quot;&quot;Extract image and mask for a single slice&quot;&quot;&quot;<br>        if sop_id not in self.dicom_data:<br>            return None, None, None<br>            <br>        ds = self.dicom_data[sop_id]<br>        image = self.preprocess_dicom_image(ds, normalize_method)<br>        <br>        # Create mask<br>        annotations = self.annotations.get(sop_id, {&#39;nodules&#39;: [], &#39;characteristics&#39;: {}})<br>        mask = np.zeros(image.shape, dtype=np.uint8)<br>        <br>        # Metadata for this slice<br>        metadata = {<br>            &#39;sop_id&#39;: sop_id,<br>            &#39;has_nodules&#39;: len(annotations[&#39;nodules&#39;]) &gt; 0,<br>            &#39;nodule_count&#39;: len([n for n in annotations[&#39;nodules&#39;] if n[&#39;inclusion&#39;]]),<br>            &#39;characteristics&#39;: annotations[&#39;characteristics&#39;],<br>            &#39;image_shape&#39;: image.shape,<br>            &#39;spacing&#39;: getattr(ds, &#39;PixelSpacing&#39;, None),<br>            &#39;slice_thickness&#39;: getattr(ds, &#39;SliceThickness&#39;, None)<br>        }<br>        <br>        # Create combined mask from all inclusion nodules<br>        for nodule in annotations[&#39;nodules&#39;]:<br>            if nodule[&#39;inclusion&#39;] and len(nodule[&#39;points&#39;]) &gt;= 3:<br>                nodule_mask = self.create_mask_from_points(nodule[&#39;points&#39;], image.shape)<br>                mask = np.maximum(mask, nodule_mask)<br>        <br>        return image, mask, metadata<br>    <br>    def save_training_data(self, patient_id, split_ratios=(0.7, 0.2, 0.1), <br>                          save_format=&#39;png&#39;, normalize_method=&#39;minmax&#39;,<br>                          min_mask_area=10):<br>        &quot;&quot;&quot;Save all slices as training data with train/val/test split&quot;&quot;&quot;<br>        <br>        # Get all slices with their data<br>        slice_data = []<br>        for sop_id in self.dicom_data.keys():<br>            image, mask, metadata = self.extract_slice_data(sop_id, normalize_method)<br>            if image is not None:<br>                # Filter by mask area if specified<br>                mask_area = np.sum(mask &gt; 0)<br>                if mask_area &gt;= min_mask_area or mask_area == 0:  # Keep negative samples<br>                    slice_data.append({<br>                        &#39;sop_id&#39;: sop_id,<br>                        &#39;image&#39;: image,<br>                        &#39;mask&#39;: mask,<br>                        &#39;metadata&#39;: metadata,<br>                        &#39;has_positive&#39;: mask_area &gt; 0<br>                    })<br>        <br>        print(f&quot;Total slices for {patient_id}: {len(slice_data)}&quot;)<br>        print(f&quot;Positive samples: {sum(1 for s in slice_data if s[&#39;has_positive&#39;])}&quot;)<br>        print(f&quot;Negative samples: {sum(1 for s in slice_data if not s[&#39;has_positive&#39;])}&quot;)<br>        <br>        # Robust train/val/test split<br>        train_ratio, val_ratio, test_ratio = split_ratios<br>        tt_ratio = val_ratio + test_ratio<br><br>        if len(slice_data) &lt;= 1 or tt_ratio &lt;= 0:<br>            train_data, val_data, test_data = slice_data, [], []<br>        else:<br>            labels = np.array([s[&#39;has_positive&#39;] for s in slice_data], dtype=np.int8)<br>            uniq, cnts = np.unique(labels, return_counts=True)<br>            can_stratify_main = (len(uniq) == 2) and (cnts.min() &gt;= 2)<br><br>            if can_stratify_main:<br>                train_data, temp_data, _, _ = train_test_split(<br>                    slice_data, labels,<br>                    test_size=tt_ratio,<br>                    stratify=labels,<br>                    random_state=42<br>                )<br>            else:<br>                print(&quot;⚠️  Not enough samples per class to stratify train/(val+test); using unstratified split.&quot;)<br>                train_data, temp_data = train_test_split(<br>                    slice_data,<br>                    test_size=tt_ratio,<br>                    random_state=42<br>                )<br><br>            # Second split: val vs test<br>            if len(temp_data) &lt;= 1:<br>                val_data, test_data = temp_data, []<br>            else:<br>                temp_labels = np.array([s[&#39;has_positive&#39;] for s in temp_data], dtype=np.int8)<br>                uniq2, cnts2 = np.unique(temp_labels, return_counts=True)<br>                val_share = (val_ratio / tt_ratio) if tt_ratio &gt; 0 else 0.0<br><br>                if (len(uniq2) == 2) and (cnts2.min() &gt;= 2):<br>                    val_data, test_data = train_test_split(<br>                        temp_data,<br>                        test_size=(1 - val_share),<br>                        stratify=temp_labels,<br>                        random_state=42<br>                    )<br>                else:<br>                    print(&quot;⚠️  Not enough samples per class to stratify val/test; using unstratified split.&quot;)<br>                    val_data, test_data = train_test_split(<br>                        temp_data,<br>                        test_size=(1 - val_share),<br>                        random_state=42<br>                    )<br>        <br>        # Save data for each split<br>        splits = [<br>            (&#39;train&#39;, train_data),<br>            (&#39;val&#39;, val_data), <br>            (&#39;test&#39;, test_data)<br>        ]<br>        <br>        all_metadata = {}<br>        <br>        for split_name, split_data in splits:<br>            if not split_data:<br>                continue<br>                <br>            print(f&quot;\nSaving {split_name} split: {len(split_data)} slices&quot;)<br>            split_metadata = {}<br>            <br>            for i, data in enumerate(split_data):<br>                # Create filename<br>                filename = f&quot;{patient_id}_slice_{i:04d}_{data[&#39;sop_id&#39;][:8]}&quot;<br>                <br>                # Save image<br>                if save_format in [&#39;png&#39;, &#39;both&#39;]:<br>                    img_path = self.output_base_dir / &quot;images&quot; / split_name / f&quot;{filename}.png&quot;<br>                    img8 = np.clip(data[&#39;image&#39;], 0, 255).astype(np.uint8)<br>                    Image.fromarray(img8, mode=&#39;L&#39;).save(img_path)<br>                <br>                if save_format in [&#39;npy&#39;, &#39;both&#39;]:<br>                    img_path = self.output_base_dir / &quot;images&quot; / split_name / f&quot;{filename}.npy&quot;<br>                    np.save(img_path, data[&#39;image&#39;])<br>                <br>                # Save mask<br>                if save_format in [&#39;png&#39;, &#39;both&#39;]:<br>                    mask_path = self.output_base_dir / &quot;masks&quot; / split_name / f&quot;{filename}.png&quot;<br>                    mask8 = (data[&#39;mask&#39;] &gt; 0).astype(np.uint8) * 255<br>                    Image.fromarray(mask8, mode=&#39;L&#39;).save(mask_path)<br>                <br>                if save_format in [&#39;npy&#39;, &#39;both&#39;]:<br>                    mask_path = self.output_base_dir / &quot;masks&quot; / split_name / f&quot;{filename}.npy&quot;<br>                    np.save(mask_path, data[&#39;mask&#39;])<br>                <br>                # Store metadata<br>                split_metadata[filename] = data[&#39;metadata&#39;]<br>            <br>            all_metadata[split_name] = split_metadata<br>        <br>        # Save metadata<br>        metadata_path = self.output_base_dir / &quot;metadata&quot; / f&quot;{patient_id}_metadata.json&quot;<br>        with open(metadata_path, &#39;w&#39;) as f:<br>            json.dump(all_metadata, f, indent=2, default=str)<br>        <br>        print(f&quot;\n✅ Saved training data for {patient_id}&quot;)<br>        print(f&quot;📁 Location: {self.output_base_dir}&quot;)<br>        <br>        return all_metadata<br>    <br><br>    def _index_cache_file(self, dicom_root, cache_dir):<br>        &quot;&quot;&quot;Return a stable cache filename for a dicom_root under cache_dir.&quot;&quot;&quot;<br>        cache_dir = Path(cache_dir)<br>        cache_dir.mkdir(parents=True, exist_ok=True)<br>        # Hash the absolute path so different roots map to different files<br>        h = hashlib.sha1(str(Path(dicom_root).resolve()).encode(&quot;utf-8&quot;)).hexdigest()[:12]<br>        return cache_dir / f&quot;dicom_index_{h}.pkl.gz&quot;<br><br><br>    def save_index_cache(self, dicom_root, sop_to_path, series_to_folder, cache_dir):<br>        &quot;&quot;&quot;Serialize index to a compressed pickle.&quot;&quot;&quot;<br>        cache_path = self._index_cache_file(dicom_root, cache_dir)<br><br>        # Convert Paths/Sets to JSON/pickle-friendly primitives for portability<br>        serializable = {<br>            &quot;meta&quot;: {<br>                &quot;dicom_root&quot;: str(Path(dicom_root).resolve()),<br>                &quot;created_at&quot;: time.time(),<br>                &quot;counts&quot;: {<br>                    &quot;sop_to_path&quot;: len(sop_to_path),<br>                    &quot;series_to_folder&quot;: len(series_to_folder),<br>                },<br>            },<br>            &quot;sop_to_path&quot;: {str(k): str(v) for k, v in sop_to_path.items()},<br>            &quot;series_to_folder&quot;: {<br>                (str(k[0]), str(k[1])): sorted({str(p) for p in folders})<br>                for k, folders in series_to_folder.items()<br>            },<br>        }<br><br>        with gzip.open(cache_path, &quot;wb&quot;) as f:<br>            pickle.dump(serializable, f, protocol=pickle.HIGHEST_PROTOCOL)<br><br>        print(f&quot;💾 Cached DICOM index → {cache_path}&quot;)    <br><br><br>    def load_index_cache(self, dicom_root, cache_dir):<br>        &quot;&quot;&quot;Load cached index if present; return (sop_to_path, series_to_folder) or (None, None) if missing.&quot;&quot;&quot;<br>        cache_path = self._index_cache_file(dicom_root, cache_dir)<br>        if not cache_path.exists():<br>            return None, None<br><br>        with gzip.open(cache_path, &quot;rb&quot;) as f:<br>            data = pickle.load(f)<br><br>        # Basic sanity check: root matches<br>        cached_root = data.get(&quot;meta&quot;, {}).get(&quot;dicom_root&quot;)<br>        if cached_root != str(Path(dicom_root).resolve()):<br>            return None, None<br><br>        # Rehydrate into your expected structures (Path, set(Path))<br>        sop_to_path = {str(k): Path(v) for k, v in data[&quot;sop_to_path&quot;].items()}<br>        series_to_folder = {}<br>        for (study, series), folders in data[&quot;series_to_folder&quot;].items():<br>            series_to_folder[(study, series)] = {Path(p) for p in folders}<br><br>        print(f&quot;✅ Loaded cached DICOM index ({data[&#39;meta&#39;][&#39;counts&#39;]})&quot;)<br>        return sop_to_path, series_to_folder<br><br><br>    def load_or_build_index(self, dicom_root, cache_dir, force_reindex=False):<br>        &quot;&quot;&quot;<br>        Try to load index cache; if missing or force_reindex=True, build and save.<br>        Returns: (sop_to_path, series_to_folder)<br>        &quot;&quot;&quot;<br>        if not force_reindex:<br>            sop_to_path, series_to_folder = self.load_index_cache(dicom_root, cache_dir)<br>            if sop_to_path is not None and series_to_folder is not None:<br>                return sop_to_path, series_to_folder<br><br>        print(&quot;🔎 Building DICOM index (no cache or force_reindex=True)...&quot;)<br>        sop_to_path, series_to_folder = self.index_dicom_tree(dicom_root)<br>        self.save_index_cache(dicom_root, sop_to_path, series_to_folder, cache_dir)<br>        return sop_to_path, series_to_folder    <br><br><br><br>    def create_dataset_info(self):<br>        &quot;&quot;&quot;Create dataset summary information&quot;&quot;&quot;<br>        info = {<br>            &#39;total_patients&#39;: 0,<br>            &#39;total_slices&#39;: 0,<br>            &#39;positive_slices&#39;: 0,<br>            &#39;negative_slices&#39;: 0,<br>            &#39;splits&#39;: {}<br>        }<br>        <br>        for split in [&#39;train&#39;, &#39;val&#39;, &#39;test&#39;]:<br>            split_dir = self.output_base_dir / &quot;images&quot; / split<br>            if split_dir.exists():<br>                image_files = list(split_dir.glob(&quot;*.png&quot;)) + list(split_dir.glob(&quot;*.npy&quot;))<br>                info[&#39;splits&#39;][split] = len(image_files)<br>                info[&#39;total_slices&#39;] += len(image_files)<br>        <br>        # Save dataset info<br>        info_path = self.output_base_dir / &quot;dataset_info.json&quot;<br>        with open(info_path, &#39;w&#39;) as f:<br>            json.dump(info, f, indent=2)<br>        <br>        print(f&quot;\n📊 Dataset Summary:&quot;)<br>        print(f&quot;   Total slices: {info[&#39;total_slices&#39;]}&quot;)<br>        for split, count in info[&#39;splits&#39;].items():<br>            print(f&quot;   {split.capitalize()}: {count} slices&quot;)<br>        <br>        return info<br><br>    def parse_lidc_xml(self, xml_path):<br>        &quot;&quot;&quot;Parse LIDC XML annotation file&quot;&quot;&quot;<br>        ns = {&#39;lidc&#39;: &#39;http://www.nih.gov&#39;}<br>        root = ET.parse(xml_path).getroot()<br><br>        def txt(elem, tag):<br>            t = elem.find(f&#39;lidc:{tag}&#39;, ns)<br>            return t.text.strip() if t is not None and t.text is not None else None<br><br>        header = root.find(&#39;lidc:ResponseHeader&#39;, ns)<br>        series_uid = txt(header, &#39;SeriesInstanceUid&#39;)<br>        study_uid  = txt(header, &#39;StudyInstanceUID&#39;)<br><br>        nodules = []<br>        for session in root.findall(&#39;lidc:readingSession&#39;, ns):<br>            for n in session.findall(&#39;lidc:unblindedReadNodule&#39;, ns):<br>                nid = txt(n, &#39;noduleID&#39;)<br>                c = n.find(&#39;lidc:characteristics&#39;, ns)<br>                characteristics = {<br>                    &#39;internalStructure&#39;: txt(c, &#39;internalStructure&#39;),<br>                    &#39;calcification&#39;: txt(c, &#39;calcification&#39;),<br>                    &#39;sphericity&#39;: txt(c, &#39;sphericity&#39;),<br>                    &#39;margin&#39;: txt(c, &#39;margin&#39;),<br>                    &#39;lobulation&#39;: txt(c, &#39;lobulation&#39;),<br>                    &#39;spiculation&#39;: txt(c, &#39;spiculation&#39;),<br>                    &#39;texture&#39;: txt(c, &#39;texture&#39;),<br>                    &#39;malignancy&#39;: txt(c, &#39;malignancy&#39;)<br>                } if c is not None else {}<br><br>                rois = []<br>                for roi in n.findall(&#39;lidc:roi&#39;, ns):<br>                    z = txt(roi, &#39;imageZposition&#39;)<br>                    sop = txt(roi, &#39;imageSOP_UID&#39;) or txt(roi, &#39;imageSOP_UID &#39;)  # Handle spaces<br>                    inc = txt(roi, &#39;inclusion&#39;)<br>                    pts = []<br>                    for em in roi.findall(&#39;lidc:edgeMap&#39;, ns):<br>                        x = int(em.find(&#39;lidc:xCoord&#39;, ns).text)<br>                        y = int(em.find(&#39;lidc:yCoord&#39;, ns).text)<br>                        pts.append((x, y))<br>                    rois.append({<br>                        &#39;z&#39;: float(z) if z is not None else None,<br>                        &#39;sop&#39;: sop,<br>                        &#39;inclusion&#39;: (inc == &#39;TRUE&#39;),<br>                        &#39;points&#39;: pts<br>                    })<br><br>                nodules.append({<br>                    &#39;SeriesInstanceUid&#39;: series_uid,<br>                    &#39;StudyInstanceUID&#39;:  study_uid,<br>                    &#39;noduleID&#39;: nid,<br>                    &#39;rois&#39;: rois,<br>                    &#39;characteristics&#39;: characteristics<br>                })<br>        return nodules<br><br><br>def index_dicom_tree(dicom_root):<br>    &quot;&quot;&quot;Index DICOM files for efficient lookup&quot;&quot;&quot;<br>    sop_to_path = {}<br>    series_to_folder = {}<br>    <br>    for dcm_path in Path(dicom_root).rglob(&quot;*.dcm&quot;):<br>        try:<br>            ds = pydicom.dcmread(dcm_path, stop_before_pixels=True, specific_tags=[&quot;SOPInstanceUID&quot;,&quot;StudyInstanceUID&quot;,&quot;SeriesInstanceUID&quot;])<br>            sop_to_path[str(ds.SOPInstanceUID)] = dcm_path<br>            key = (str(getattr(ds, &quot;StudyInstanceUID&quot;, &quot;&quot;)),<br>                   str(getattr(ds, &quot;SeriesInstanceUID&quot;, &quot;&quot;)))<br>            series_to_folder.setdefault(key, set()).add(dcm_path.parent)<br>        except Exception as e:<br>            print(f&quot;[index] Skip {dcm_path}: {e}&quot;)<br>    return sop_to_path, series_to_folder<br><br><br>def resolve_series_folder(annotations, series_to_folder):<br>    &quot;&quot;&quot;Find DICOM folder based on series info from XML&quot;&quot;&quot;<br>    if annotations:<br>        key = (annotations[0][&#39;StudyInstanceUID&#39;], annotations[0][&#39;SeriesInstanceUid&#39;])<br>        if key in series_to_folder:<br>            # If multiple folders found, pick the one with most DICOMs<br>            folders = list(series_to_folder[key])<br>            folders.sort(key=lambda p: len(list(p.glob(&quot;*.dcm&quot;))), reverse=True)<br>            return folders[0]<br>    return None<br><br>def resolve_any_sop_path(annotations, sop_to_path):<br>    &quot;&quot;&quot;Find any DICOM file path from ROI SOP UIDs&quot;&quot;&quot;<br>    for a in annotations:<br>        for r in a[&#39;rois&#39;]:<br>            sop = r.get(&#39;sop&#39;)<br>            if sop and sop in sop_to_path:<br>                return sop_to_path[sop]<br>    return None<br><br><br>def process_multiple_patients(base_xml_dir, dicom_root):<br>    &quot;&quot;&quot;Process multiple patients from XML annotations and DICOM files&quot;&quot;&quot;<br>    converter = DICOMToTrainingDataConverter(output_base_dir=&quot;lung_nodule_dataset&quot;)<br><br>    xml_files = list(Path(base_xml_dir).glob(&quot;**/*.xml&quot;))<br>    print(f&quot;XML files found: {len(xml_files)}&quot;)<br><br>    sop_to_path, series_to_folder = index_dicom_tree(dicom_root)<br><br>    processed = 0<br>    for i, xml_path in enumerate(xml_files): <br>        print(f&quot;\n🔄 Processing {i+1}/{len(xml_files)}: {xml_path.name}&quot;)<br><br>        try:<br>            annotations = converter.parse_lidc_xml(xml_path)<br><br>            # Try to find matching DICOM folder<br>            folder = resolve_series_folder(annotations, series_to_folder)<br>            if folder is None:<br>                sop_file = resolve_any_sop_path(annotations, sop_to_path)<br>                if sop_file:<br>                    folder = sop_file.parent<br><br>            if folder is None:<br>                print(f&quot;🚫 No matching DICOM folder for {xml_path.name}. Skipping.&quot;)<br>                continue<br><br>            print(f&quot;📂 Using DICOM folder: {folder}&quot;)<br>            converter.load_dicom_series(folder)<br>            converter.parse_annotations(annotations)<br><br>            patient_id = f&quot;patient_{i+1:04d}&quot;<br>            converter.save_training_data(<br>                patient_id=patient_id,<br>                save_format=&#39;both&#39;,<br>                normalize_method=&#39;hu_window&#39;,<br>                min_mask_area=10<br>            )<br><br>            processed += 1<br><br>        except Exception as e:<br>            print(f&quot;❌ Error processing {xml_path.name}: {e}&quot;)<br><br>        finally:<br>            converter.dicom_data.clear()<br>            converter.annotations.clear()<br><br>    print(f&quot;\n✅ Finished. Patients processed: {processed}&quot;)<br>    converter.create_dataset_info()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    process_multiple_patients(&quot;./LIDC-XML-ANNOT/tcia-lidc-xml&quot;, &quot;./LIDC-IDRI-NBIADataRetriever&quot;)</pre><p>Log history from the code :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVuSvDaazkHyix40L0OF1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*sV5F-c3F8jlQJ6vNUYwhtA.png" /></figure><p>Directory structure of the stored data :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*LzFKIRCpBhShylLzOFHm5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*CJbWRwuXsBnEzmhqSueXuA.png" /></figure><p>Patient metadata content :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*G6My0EzpfZOPH8zhHSzUyw.png" /></figure><p>To sum up, segmentation data for 228 patients were prepared. In total 80,008 CT slices — 55,788 slices for the training, 15,830 slices for validation, and 8,390 slices for testing.</p><p>Next step would be to use this data to train the model!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0667da1c7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Medical Image Visualization]]></title>
            <link>https://medium.com/@hannah.hj.do/medical-image-and-visualization-b204e6a1b1d1?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/b204e6a1b1d1</guid>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[dicom]]></category>
            <category><![CDATA[nifti]]></category>
            <category><![CDATA[pydicom]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 12:36:16 GMT</pubDate>
            <atom:updated>2025-09-18T04:26:13.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*D541Xm0ijNaNHTHoEerCgA.gif" /></figure><p>Medical image file formats are quite different from the general image formats we’re familiar with— <strong>JPEG</strong> or <strong>PNG</strong>. In healthcare, the dominant standard is <strong>DICOM (Digital Imaging and Communications in Medicine)</strong>.</p><h3>DICOM</h3><p>DICOM files are typically <strong>less compressed</strong>, in order to preserve both the <strong>full pixel data</strong> and the <strong>metadata.</strong></p><p>Some key characteristics of DICOM data include:</p><ul><li><strong>Rich metadata</strong>: Each file can store patient details (e.g., name, age, ID), acquisition information (scanner type, date, imaging protocol), and hospital identifiers. This makes <strong>data security and privacy</strong> a critical concern.</li><li><strong>Vendor-specific acquisition</strong>: Companies such as <strong>Philips, GE, Siemens, and Canon</strong> use unique hardware designs and proprietary reconstruction algorithms to acquire and process the raw data before exporting it into DICOM. Although the output is standardized, additional vendor-specific metadata fields are often embedded.</li><li><strong>Large file sizes</strong>: Medical images are far larger than typical photos. For example, a <strong>pathology whole-slide image</strong> can reach dimensions of <em>10,000 × 10,000 pixels</em>, while a typical <strong>MRI scan</strong> may contain a 3D volume of <em>512 × 512 × 256 voxels</em>. A single CT scan series can easily exceed hundreds of megabytes.</li><li><strong>Interoperability</strong>: Despite differences in acquisition methods, DICOM ensures that images can be shared across hospitals, PACS (Picture Archiving and Communication Systems), and analysis tools.</li></ul><h4>Data Dictionary</h4><p><strong>DICOM Data Dictionary </strong>lists all data elements (attributes) that appear inside a DICOM file.</p><p>Data elements include :</p><ul><li><strong>Tag</strong> (a pair of hexadecimal numbers like (0010,0010))</li><li><strong>Name</strong> (e.g., <em>Patient Name</em>)</li><li><strong>VR (Value Representation)</strong>, meaning the data type (e.g., string — CS, SH, LO, … , datetime — DA, TM, DT, …, binary — AE, UI)</li><li><strong>VM (Value Multiplicity)</strong>, meaning how many values are allowed</li></ul><h4>IOD</h4><p><strong>Information Object Definition — </strong>is the grammar or rules for using data dictionary. It requires patient module (name, ID, BOD, …), study module (study date, accession number), pixel module (rows, columns, pixel data), and etc. IOD basically <strong>connects the data dictionary with the actual image instances </strong>stored in DICOM files.</p><p>As a result a DICOM file metadata may look as the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*NsZCdWlBLRsoRAYgJZAjKA.png" /></figure><h3>NIFTI</h3><p>NIFTI — Neuroimaging Informatics Technology Initiative is also a standardized way to store medical images. It can support 3D, 4D datasets (3D volumes over time) — unlike DICOM, which stores one slice per file.</p><p>NIFTI focuses purely on imaging and coordinate information — it does not include patient identifiers, hospital details, or clinical metadata. File extensions are in the format of .nii,.nii.gz, and there are two data type versions :</p><ul><li><strong>NIFTI-1</strong>: Uses 8-bit representation (up to 256 values).</li><li><strong>NIFTI-2</strong>: Uses 64-bit representation (up to 1.8446744 × 1⁰¹⁹ values), suitable for much larger datasets.</li></ul><h3>How to Visualize Medical Images</h3><h4>GUI — 3D Slicer</h4><p>To easily visualize medical data, <strong>3D Slicer</strong> is widely used — primarily in radiology and related domains. It is particularly well known for handling <strong>volumetric imaging modalities</strong> such as <strong>CT, MRI, and PET</strong>. Key functionalities include <strong>visualization, segmentation, registration, and quantitative analysis</strong> of 3D datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*BSXA91_EWY-ccT2GCD0kUQ.png" /><figcaption>axial — XY (top left), coronal — XZ (bottom left), sagittal — YZ (bottom right)</figcaption></figure><h4>Python</h4><p>The data can be also visualized via Python using multiple libraries.</p><ol><li>Downloading Data</li></ol><p>Here I have selected to download data from the Cancer Imaging Archive — specifically<a href="https://www.cancerimagingarchive.net/collection/lidc-idri/"> The Lung Image Database Consortium (LIDC) and Image Database Resource Initiative (IDRI): A completed reference database of lung nodules on CT scans.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5Hq_PnZ_74ke0WI8APnEw.png" /><figcaption><a href="https://www.cancerimagingarchive.net/collection/lidc-idri/">https://www.cancerimagingarchive.net/collection/lidc-idri/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iON75-CYGbN3FkWftat8hQ.png" /><figcaption>NBIA Data Retriever</figcaption></figure><p>2. Reading &amp; Visualizing Data</p><p>The data can then be imported and visualized via <em>pydicom</em> and <em>matplotlib</em> library.</p><pre># ! pip install &quot;pydicom==2.3.1&quot;<br># ! pip install dicom2nifti<br><br>import pydicom<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>from pathlib import Path<br><br>from skimage.util import montage<br><br>import dicom2nifti<br>import nibabel as nib<br>import numpy as np<br><br>base_path = &#39;../LIDC-IDRI_DICOM&#39;<br>dicom_img_list = list(Path(base_path).glob(&#39;*/*/*/*.dcm&#39;))<br><br>def show_metadata(dataset):<br>    print(&quot;Patient&#39;s ID............ :&quot;, dataset.get(&quot;PatientID&quot;))<br>    print(&quot;Modality................ :&quot;, dataset.get(&quot;Modality&quot;))<br>    print(&quot;Body Part Examined...... :&quot;, dataset.get(&quot;BodyPartExamined&quot;))<br>    print(&quot;View Position........... :&quot;, dataset.get(&quot;ViewPosition&quot;))<br>    print(&quot;Image Position.......... :&quot;, dataset.get(&quot;ImagePositionPatient&quot;))<br><br>    if &#39;PixelData&#39; in dataset:<br>        rows = int(dataset.Rows)<br>        cols = int(dataset.Columns)<br>        print(&quot;Image Size.............. : {rows:d} x {cols:d}, {size:d} bytes&quot;.format(<br>            rows=rows, cols=cols, size=len(dataset.PixelData)<br>        ))<br>        if &#39;PixelSpacing&#39; in dataset:<br>            print(&quot;Pixel spacing........... :&quot;, dataset.PixelSpacing)<br><br>def visualize_image(dataset, figsize=(10,10)):<br>    plt.figure(figsize=figsize)<br>    plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)<br>    plt.show()<br><br>show_metadata(dcm_img)<br>visualize_image(dcm_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*oEy0BjWoZlITvvK6RyHtBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*WHFl-AFOj27p8WGN0RLcOQ.png" /></figure><p>3. Converting DICOM to NIFTI</p><p><em>dicom2nifti</em> library can also easily convert data from DICOM to NIFTI format, which can be re-imported and visualized as well via <em>nibabel</em> library.</p><pre>base_path = &#39;../LIDC-IDRI_DICOM/LIDC-IDRI-0001/30178/03192&#39; <br># dcm bundle folder path<br>dicom2nifti.convert_directory(base_path, &quot;./&quot;)<br><br>nifti_path = &#39;./3000566.nii.gz&#39; # name of the created nifti file<br>sample_img = nib.load(nifti_path)<br>sample_img_obj = np.asanyarray(sample_img.dataobj)<br>print(f&#39;nifti file shape (h, w, d) : {sample_img.shape}&#39;)<br><br>transpose_img = sample_img_obj.transpose((2,1,0))<br>plt.figure(figsize=(10,10))<br>plt.imshow(montage(transpose_img))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Qnf1HZfuRdHSK_Kp7wb8Qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*DJclVTZWv1YGbmStf6gFlA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b204e6a1b1d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy your app on Google Cloud Run]]></title>
            <link>https://medium.com/@hannah.hj.do/how-to-deploy-your-app-on-google-cloud-run-e3b9b61a26b3?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3b9b61a26b3</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 25 May 2024 01:54:20 GMT</pubDate>
            <atom:updated>2024-05-25T01:54:20.330Z</atom:updated>
            <content:encoded><![CDATA[<p>On my last post, I have used Azure Container Registry and Container Instance to deploy my app. However having everything simplified with fewer configuring options led to slight inconvenience. As time passed by, my app seemed unstable with an increasing number of concurrent users, and the logs did not provide enough information about the error.</p><p>Looking for an alternative, I found Cloud Run in Google Cloud Platform for deploying containerized apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqTMNJtFeP-gigm1Gjq85w.png" /><figcaption>console.cloud.google.com/run</figcaption></figure><p>In order to set up a service, you can use Google Cloud Console (as shown above), but I found using Google Cloud CLI simpler.</p><p>Following is a reference to installing the CLI : <a href="https://cloud.google.com/sdk/docs/install">https://cloud.google.com/sdk/docs/install</a></p><p>Assuming you have an account set up on Google Cloud, first thing to be done is initializing the project.</p><p>gcloud init will show following options for setting basic configuration — if it is your first time using gcloud cli, you will need to create a new configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9OzO-J1MzQLjn1sCDl7hw.png" /><figcaption>gcloud init</figcaption></figure><p>Make sure to log in with the right email account associated with your google cloud platform, select a configuration name, and pick/create a cloud project to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrBI5X8MHvJVwzqpzbtF5Q.png" /><figcaption>Setting default compute engine region is optional</figcaption></figure><p>Next step is to deploy your docker app.</p><p>Google Cloud Run documentation recommends to tag &amp; push the image on Docker Hub first and then deploy on Cloud Run.</p><p>The commands are as follows :</p><p>docker build . -t {image_name}:{tag}</p><p>docker tag {image_name}:{tag} {docker_hub_user_name}/{image_name}:{tag}</p><p>docker push {docker_hub_user_name}/{image_name}:{tag}</p><p>gcloud run deploy {cloud_run_service_name} --image docker.io/{docker_hub_user_name}/{image_name}:{tag} --timeout=300 --concurrency=100</p><p>If you wish to update the service on settings such as max timeout seconds or concurrent users, you can run the following command :</p><p>gcloud run services update --timeout={timeout_sec} --concurrency={concurrent_num}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgVRXAPC6EWWV0QmgYBpEA.png" /><figcaption>gcloud run deploy ~</figcaption></figure><p>After specifying the region, and determining if the app would be accessed by the public, you will be able to find the created service on Google Cloud console in few minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Eetk4tyckcKB0f-_w9NHA.png" /></figure><p>I found it quite useful to have a metric dashboard of request counts, latencies, container instance counts, CPU &amp; memory utilization, and etc. right on the home screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIvnTG7aQ_04dibyYnedww.png" /></figure><p>The logs were quite detailed and user friendly — easy to access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-R3GonU8Ipx0jPCP9lQ0pw.png" /><figcaption>Google Cloud Run Logs</figcaption></figure><p>There is also an option for a minimum number of instances — setting it to 0 — allowing cold starts in case the API is not accessed as often to reduce billling. On the other hand, setting the minimum number of instance to more than 1 will reduce latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*sHBDAdsmb1CjQ_Zwcy1wZA.png" /></figure><p>You can allow the app to be accessed by public, your project or by a shared VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CG1zubYUqz0knkrcipftA.png" /></figure><p>You can set authentication step by Cloud IAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c8y5va80ehtsGutQjZwVAg.png" /></figure><p>And set up Cloud Build to allow CI-CD from your own GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*8ZJ91OXqyr1VTHSqWmE8MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*HSBexpTIUXeMT83V2vPWxg.png" /></figure><p>Lastly, Cloud Run provides a static URL that starts with the project name, along with the option of setting custom domain name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsZBvjVGe9HfOCblidIUNA.png" /></figure><p>The pricing is quite reasonable in how <a href="https://cloud.google.com/run/pricing">Cloud Run only charges you for the resources you use, rounded up to the nearest 100 millisecond.</a></p><p>Overall, I found the user interface and deployment process to be quite intuitive. 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3b9b61a26b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy your app on Azure Container Instance]]></title>
            <link>https://medium.com/@hannah.hj.do/how-to-deploy-your-app-on-azure-container-instance-5e881b5a1ee0?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e881b5a1ee0</guid>
            <category><![CDATA[registry]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[instance]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Thu, 09 May 2024 09:54:04 GMT</pubDate>
            <atom:updated>2024-05-10T03:11:50.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VChIPerArt4DG094cPTzVw.png" /><figcaption>portal.azure.com</figcaption></figure><p>Similar to Elastic Container Service on AWS, Microsoft Azure provides Azure Container Instance (ACI), a container service for deploying and managing your container app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GpkNOp0VJy43UieAKnskw.png" /></figure><p>Prior to using Azure Container Instance (ACI), Microsoft Azure suggests users to have accounts that ends with “.onmicrosoft.com” for Azure portal. Each user needs to have access to a ‘subscription’ as a means of billing system. A unique subscription ID will be given to manage billing, track resource usage, and organize resources within the Azure platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KaaHXslzkMGYnijjysf8A.png" /></figure><p>Deploying your app on ACI is made easy by setting up a Container Registry for your docker images — quite similar to ECR in AWS. Encryption can be set up on Azure so that your images or artifacts can be automatically encrypted when pushed and decrypted when pulled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3JppZ_N8_ja9QqoIslWxQ.png" /><figcaption>Private access is available for premium pricing plans</figcaption></figure><p>To upload your local docker image, you need <a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">Azure CLI</a> installed on your local host machine, and access key retrieved from the container registry (Container registry &gt; Settings &gt; Access keys). Also make sure to click on the checkbox in Access keys if you are the admin user trying to access the Container Registry.</p><pre>az login<br>az acr login --name {name of the container registry}<br><br>docker tag {local_image} {name of the container registry}/{local_image}<br>docker push {name of the container registry}/{local_image}<br><br>## alternative : {name of the container registry}.azurecr.io/{local_image}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*iTu2cUUinB5zXX5nMz6J0A.png" /><figcaption>Azure Container Registry &gt; Access Keys &gt; “click on the checkbox if you are admin”</figcaption></figure><p>After accessing the login server with retrieved password (Access Keys), run the docker commands to push your local image to Azure Container Registry.</p><p>With the uploaded image, you can launch the container instance with quite few configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4P1mAWt9yzgOrXDbQv56Q.png" /></figure><p>Selection of subscription, region, image source (Azure Container Registry), CPU and memory size is required along with the DNS name label and allowable ports. CPU can be selected up to 8, while Memory up to 32 GiB (depends on the region).</p><p>Optional settings include restart policy and environment variables / key management. Default OS type is Linux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdWn19C55rELZQmCeWvFkQ.png" /></figure><p>After a few minutes of booting the instance, you will be provided with a temporary public IP address and static FQDN (fully qualified domain name) for the host where you can access your docker images. In my case, a swagger UI for a FastAPI app— “{public ip}:8000/docs”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgsraatnnDiKB1MekE7cHQ.png" /></figure><p>As you can see, deploying containers with ACI is quite simple, without the need to manage VMs or clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OW1hUEpPUHQWGzTPn2Owhg.png" /><figcaption>ACI Activity Logs</figcaption></figure><p>More importantly, ACI automatically allocates resources based on the demand/traffic of the application, along with monitoring options provided on the console. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e881b5a1ee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anthropic’s Claude 3 for Paragraph Segmentation (Korean)]]></title>
            <link>https://medium.com/@hannah.hj.do/anthropics-claude-3-for-paragraph-segmentation-korean-84f9ddffea22?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f9ddffea22</guid>
            <category><![CDATA[anthropics]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[claude-3]]></category>
            <category><![CDATA[sonnet]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 16:00:11 GMT</pubDate>
            <atom:updated>2024-03-10T00:57:47.392Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJO9RhaD8PXSqhxzPwg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOHlqdG1rZmg2Z2xobmN1ZDdtZ3EzZm50ODhvbDd4NDJuZmFnYjExMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FJO9RhaD8PXSqhxzPwg%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaHUyMzY3a3BueGMwN2sxdnlqb2pwM3hqa2ljdHljMTIwaGJ3ODhyeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FJO9RhaD8PXSqhxzPwg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0ee45af853d584f325661bda4041f6/href">https://medium.com/media/1b0ee45af853d584f325661bda4041f6/href</a></iframe><p>I am happy to share that Anthropic now provides a console website for API access, including usage reports, billing invoices, <a href="https://docs.anthropic.com/claude/reference/errors">error documentation</a>, and so much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLdd2lJCZUdIWy4EsJ_npw.png" /><figcaption><a href="https://console.anthropic.com/dashboard">https://console.anthropic.com/dashboard</a></figcaption></figure><p>The rate limit issue that I experienced with Amazon Bedrock’s Claude-2.1 has also been resolved with the direct API access via Anthropic’s console website.</p><p>Claude models are now available in various tiers depending on usage, which means individuals or small business owners can now access Anthropic’s models. 🙌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnknNiA0b9yMikNRpzer9A.png" /><figcaption>Rate Limits for each Tier - Anthropic’s Claude</figcaption></figure><p>When comparing the rate limits of Claude with GPT-4, Anthropic provides larger token limit as the tier goes up, whereas OpenAI provides more requests per minute. Anthropic also provides a ‘custom’ option to scale the token and request limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*2JfOcdYWSzOTrUS8eZtO1g.png" /><figcaption>Token and Rate limits for Anthropic &amp; OpenAI on Tier 4</figcaption></figure><p>Most importantly, the performance of both Sonnet and Opus with Claude 3 models have been remarkable.</p><p>I mainly work with OpenAI’s GPT-4 to segment Korean sentences into paragraphs. The difficult part in prompt tuning was that GPT-4 tends to auto-correct grammar, remove or add spaces in between, and finds it difficult to associate the index of each sentence and the context between the sentences. Specifying the details in the prompts didn’t seem to improve the performance.</p><p>For example, the input list of sentences is as follows :</p><pre>[&quot;글을 쓴다는 게 굉장히 즐거운 일이기도 한데 사실 좀 고통스러운 일이기도 하거든요&quot;,<br>&quot;제일 중요한 부분은 ~이 아닐까 싶어요 조급해 하지 마셨으면 좋겠어요&quot;, <br>&quot;스트레스를 받으면 내가 오래 ~을 할 수가 없잖아요&quot;, <br>&quot;참고로 최근에 새롭게 관심이 생긴 영화가 있어요&quot;] </pre><p>To work around the errors, I have set the expected output in the format of [{“start”: #, “end”: #}, {“start”: #, “end”: #}, …] — indicating the start and end index of each segment to form paragraphs.</p><p>The output for the sentences list above should have been as the following :</p><pre>[{&quot;start&quot;: 1, &quot;end&quot;: 3}, {&quot;start&quot;: 4, &quot;end&quot;: 4}]<br><br># Segments 1 to 3 include the same theme of stress management,<br># Segment 4 starts a new context.</pre><p>However GPT-4 was prone to errors such as returning nonexistent indices such as {“start”: 5, “end”: 8}, not to mention the duplicate indices {“start”: 8, “end”: 8}.</p><p>With Claude-2.1, this type of error could be kept under control as long as the length of the sentences list was less than 5.</p><p>With <strong>Claude 3 (Sonnet &amp; Opus)</strong> the length of the sentences could be stretched to a list of more than 10 sentences with higher accuracy in segmentation, allowing bigger chunk of texts to be processed at a time. None of the previous issues encountered with GPT were found in Claude 3. This indicates that Claude 3 can associate the sequence number of each sentence while understanding the context between the sentences.</p><p>And of course, the result for paragraph segmentation turned out much satisfiable compared to GPT-4.</p><p>The pricing for the models are also quite reasonable.</p><p>For Claude 3’s Sonnet model, the price for input tokens are 1/10th price, and the output tokens are 1/2 price of that of OpenAI’s GPT-4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fY-w1ZWuR9_ukEbqGtu_pA.png" /><figcaption>Pricing based on Input and Output tokens — gpt-4, gpt-4–1106-preview, sonnet, opus</figcaption></figure><p>For Claude 3’s Opus model, the input token price is cheaper ($15 / $30) however the output token price is slightly more expensive ($75 / $60) than GPT-4.</p><p>In my case of requiring short output compared to input size, Opus could be considered a reasonable price. However for users who utilize the model for creative writing, the pricing could be a barrier.</p><p>I would recommend any developers working with LLM to try Anthropic’s Claude 3, definitely a breakthrough in prompt engineering.</p><pre>class AnthropicClient:<br>    def __init__(self):<br>        self.anthropic = anthropic.Anthropic(            <br>            api_key=os.environ.get(&quot;ANTHROPIC_API_KEY&quot;)<br>        )<br>        <br>    def request_to_sonnet(<br>        self, prompt, texts<br>    ):<br>        response = self.anthropic.messages.create(       <br>            model=&quot;claude-3-sonnet-20240229&quot;,<br>            max_tokens=4096,<br>            temperature=0,<br>            messages=[<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt + str(texts)}<br>            ]<br>        )   <br>        return response.content[0].text</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f9ddffea22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to access Claude-2.1 via AWS Bedrock]]></title>
            <link>https://medium.com/@hannah.hj.do/how-to-access-claude-2-1-via-aws-bedrock-3e322cfe107e?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e322cfe107e</guid>
            <category><![CDATA[claude-2]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 01:45:14 GMT</pubDate>
            <atom:updated>2024-03-16T03:17:50.772Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohuPDuPHDuGnVtp5u%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYXoyYW5yZDFhN3pmMzNnNHEwdjNkOGo4a3Jnbnp5NTJwcDkzZXhwZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ohuPDuPHDuGnVtp5u%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcmUyY3p1bnQ5eDBieDY4OGdtbG5nZjFoaXVycGsxb2FoMnl3Z3h5ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ohuPDuPHDuGnVtp5u%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/be360144e1152b08a5350d8c29b4f156/href">https://medium.com/media/be360144e1152b08a5350d8c29b4f156/href</a></iframe><p>I had been waiting for the Claude API to be approved for over three weeks on both Google Vertex AI and direct API request to Anthropic.. until I realized Anthropic’s Claude was also released as part of Amazon Web Service’s Bedrock.</p><p>AWS Bedrock service wasn’t yet opened in Seoul region so I switched Tokyo region (ap-northeast-1) and submitted API request.</p><p>The request was approved in only few minutes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiqXUC2SBXhUWOhmeuVvpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMn8ClnQHfUsMgs-oE-8iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNfv_mHEmH1-YAr3BlUkCQ.png" /></figure><p>Excited to test out the results, I created a new client for Claude with basic information, added boto3 to my virtual environment (poetry), updated aws cli, and stored aws account information (aws configure) on my server.</p><ul><li>access key, secret key, and region as “ap-northeast-1”</li></ul><pre>class ClaudeClient:<br>    def __init__(self):<br>        self.bedrock = boto3.client(<br>            service_name=&#39;bedrock-runtime&#39;,<br>            region_name=&quot;ap-northeast-1&quot;<br>        )<br><br>    async def async_request_to_claude(<br>        self, prompt, texts<br>    ):<br>        body = json.dumps({<br>            &quot;prompt&quot;: &#39;&quot;\n\nHuman:&#39; + prompt + &#39; &#39;.join(texts) + &#39;\n\nAssistant:&#39;,<br>            &quot;max_tokens_to_sample&quot;: 10000,<br>            &quot;temperature&quot;: 0.75<br>        })<br>        <br>        model = &#39;anthropic.claude-v2:1&#39;<br>        <br>        response = self.bedrock.invoke_model(body=body, modelId=model, accept=&#39;application/json&#39;, contentType=&#39;application/json&#39;)<br>        <br>        return response <br><br>    async def validate_claude_response(<br>        self, system_prompt, user_prompt, retry_count: int = 5<br>    ):        <br>        for attempt in range(retry_count):<br><br>            try: <br>                claude_response = await self.async_request_to_claude(<br>                    system_prompt, user_prompt<br>                ) <br>                if claude_response:                    <br>                    content = json.loads(claude_response.get(&#39;body&#39;).read())[&#39;completion&#39;]                               <br>                    response = json.loads(content)   <br>                    return response <br><br>            except Exception as e:<br>                logger.info(&quot;Trying again after 3 seconds - %s&quot;, e)<br>                await asyncio.sleep(3)<br><br>      # validation step simplified for visual aid</pre><p>Using the validate_claude_response function, I tested out Claude-2.1 and Claude Instant (out of curiosity), in which Claude-2.1 performed much better in basic segmentation tasks.</p><p>The tasks specifically involved segmenting Korean sentences from a list of words. Compared to GPT-4, Claude-2.1 was much easier to tune as it consistently followed the provided prompts. Meanwhile GPT-4 kept auto-correcting the sentences, adding or removing spaces, even when specified not to.</p><p>The performance of Claude-2.1 is much satisfying in a way that it precisely follows instructions without any unexpected deviations. I also found Claude-2.1’s results with Korean grammar and sentence segmentation highly accurate.</p><p>For those who are interested in deploying the code (VM with Docker &amp; FastAPI), following is the content of my Dockerfile, which is quite simple as Poetry took care of packaging and dependency management.</p><pre>FROM python:3.9<br><br>RUN pip3 install poetry<br>RUN pip3 install uvicorn<br><br>COPY . .<br><br>RUN poetry config virtualenvs.create false<br>RUN poetry install --no-dev --no-root<br><br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Similar to different services in AWS, there are On-Demand, Batch, and Provisioned option when it comes to pricing.</p><p>The cost of Anthropic’s Claude 2.1 (On-Demand) on Amazon Bedrock was the same as the price provided from Anthropic’s website. Still $ 8.00 (prompt) and $24.00 (completion) per million tokens, where as OpenAI’s GPT-4 costs $10 (prompt) and $30 (completion) per million tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyYUoiy3K2oh5fTJpU6muw.png" /></figure><p>However the rate limit of Amazon Bedrock and the speed of Claude-2.1, leave a bit to be desired.</p><p>Whereas OpenAI’s GPT-4 provides different tiers to RPM (rate limit per minute),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK9G-l7Kb3WGx8OhihMG4g.png" /></figure><p>Amazon Bedrock’s Runtime quota has a fixed rate of requests processed per minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2k3ofj7noVW9VgPH-BskBw.png" /></figure><p>In addition, random throttling exception issues have been occurring despite the token counts and requests being way below the limits.</p><p>I’m hoping this feature can be improved as more users migrate to AWS.</p><p>If you have any other ideas or suggestions for boosting the number of requests Claude-2.1 can handle per minute, I’d love to hear them, thanks! :)</p><h3>Update 1</h3><p>I submitted questions on AWS re:Post and AWS Support (service quota increase) regarding the throttling error. Unfortunately I wasn’t able to obtain any constructive response from the AWS re:Post.</p><ul><li>AWS re:Post : <a href="https://repost.aws/questions/QUC82MTlWlQNagsqEG2Hbxlw#ANr2vummWORhStDkUsURpPuA">https://repost.aws/questions/QUC82MTlWlQNagsqEG2Hbxlw#ANr2vummWORhStDkUsURpPuA</a></li></ul><p>On the contrary, the answers from AWS Support were quite straight forward.</p><p>The conversations sum up to the following :</p><pre>Q) Current quota for Claude requests is 100 requests and 200,000 tokens per minute.<br>According to what you have mentioned, is this capacity shared across all customers?<br><br>A) Yes that is correct as the capacity is shared accross all the customers.</pre><p>Following are some of the screen captures of the conversation for reference :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEQydpqfDKxe0qjbPsKvPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6n3tvECEAEjGu3T7hMi8fw.png" /></figure><p>Apparently current quota for Claude-2.1 (100 requests and 200,000 tokens per minute) is shared across all users in Tokyo Region.</p><p>This means that Runtime models provided on AWS Bedrock, especially Claude-2.1 is unavailable for those who plan to use the model for practical or commercial use.</p><p>Considering how the same model with Provisioned Throughput has higher cost and is allowed with increase in rate limits, I would assume that Anthropic’s focus is more towards large corporations rather than small businesses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01YXJmtZcnhI1RBfoSCSFg.png" /><figcaption>Pricing of Provisioned Throughput on Anthropic’s Claude-2.1</figcaption></figure><p>From a personal perspective, this situation is less than ideal, however will have to look for alternative models that offer comparable performance, especially considering the recent rapid advancements in LLMs.</p><h3>Update 2</h3><p>The introduction of the Anthropic console website resolved the rate limit issue! 🙏</p><p>➡️ <a href="https://console.anthropic.com/dashboard">https://console.anthropic.com/dashboard</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e322cfe107e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Glossary of Terms : async & sync, single & multi-threading, blocking & non-blocking]]></title>
            <link>https://medium.com/@hannah.hj.do/glossary-of-terms-async-sync-single-multi-threading-blocking-non-blocking-90500cb01296?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/90500cb01296</guid>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[non-blocking]]></category>
            <category><![CDATA[blocking]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 01:56:11 GMT</pubDate>
            <atom:updated>2024-02-03T01:56:11.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Glossary of Terms : async &amp; sync, single &amp; multi-threading, blocking &amp; non-blocking</h3><h3>Async &amp; Sync</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoElX9lbcALpne9eoznMFQ.png" /><figcaption>Bitbytesoft — synchronous and asynchronous</figcaption></figure><p>Both synchronous and asynchronous programming can be required depending on the type of a program or a function. A synchronous programming executes tasks one at a time, waiting for a previous task to be finished before moving onto another. This can be reliable in a a program that relies on completion in a sequential order.</p><p>Asynchronous programming on the other hand does not rely on a task to occur in a specific order. It can be used in situations where tasks should be handled without blocking the main thread, and to do multiple tasks that can be processed at the same time. This leads to a big impact on the speed, reliability, and scalability of the application.</p><p>My case of using asynchronous programming was to enhance performance in a text processing pipeline that involves sending multiple requests to different APIs. After refactoring the code from sync to async for the API requests that did not depend on each other via python asyncio, the total duration metric changed from minutes to seconds.</p><h3>Single &amp; Multi-threading</h3><p>Whereas sync and async is about tasks, threading is about workers. Multi-threading is a form of concurrency where multiple threads can run in parallel. Single threading meaning a single thread works by itself. Multithreading can improve the performance and efficiency of a program by utilizing the available CPU resources more effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvDGFFONG1N5oetN55aBeg.png" /><figcaption>GeeksForGeeks — Multi-threading in OS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bb2Hwm9FmWYvJ2yIrpiKgA.png" /><figcaption>stackacademic — Multithreading vs Asynchronous programming</figcaption></figure><h3>Blocking &amp; Non-blocking</h3><p>Blocking is when a function holds <strong>control</strong> until finishing a task. For example, while waiting for a laundry, not being able to do anything else. While non-blocking is handing over control to another function while finishing for current task. For example, watching Netflix while waiting for the laundry.</p><p>Blocking &amp; non-blocking is a different concept from async &amp; sync — following are some examples referenced from a blog (exmemory - tistory) :</p><ul><li>Blocking &amp; Synchronous : Hand-washing the laundry (block), then hanging out the laundry (synchronous)</li><li>Blocking &amp; Asynchronous : Watching Netflix while waiting for the laundry (asynchronous), waiting for the laundry to be done to hang out the laundry (block)</li><li>Non-blocking &amp; Synchronous : Watching Netflix while waiting for the laundry + checks if the laundry is done once in a while (Non-block), Checks if the laundry is done once in awhile and then hangs out the laundry when it’s done (synchronous)</li><li>Non-blocking &amp; Asynchronous : After running the washing machine, loading the dish-washer and then vacuuming the room. (non-block) After vacuuming the room, finding the dish-washer finished earlier than the washing machine — drying the dishes before moving the clothes to the dryer (asynchronous)</li></ul><h3>References</h3><ul><li><a href="https://www.baeldung.com/cs/async-vs-multi-threading">https://www.baeldung.com/cs/async-vs-multi-threading</a></li><li><a href="https://bitbytesoft.com/synchronous-and-asynchronous-programming/">https://bitbytesoft.com/synchronous-and-asynchronous-programming/</a></li><li><a href="https://www.geeksforgeeks.org/multithreading-in-operating-system/">https://www.geeksforgeeks.org/multithreading-in-operating-system/</a></li><li><a href="https://exmemory.tistory.com/78">https://exmemory.tistory.com/78</a></li><li><a href="https://blog.stackademic.com/multithreading-vs-asynchronous-programming-f015c6b676d0">https://blog.stackademic.com/multithreading-vs-asynchronous-programming-f015c6b676d0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90500cb01296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anthropic’s Claude 2 vs. Google Vertex AI’s PaLM 2]]></title>
            <link>https://medium.com/@hannah.hj.do/anthropics-claude-2-vs-google-vertex-ai-s-palm-2-eb05422a5a43?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb05422a5a43</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[anthropics]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[palm]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 02:04:53 GMT</pubDate>
            <atom:updated>2026-01-12T05:48:31.211Z</atom:updated>
            <content:encoded><![CDATA[<p>As an OpenAI GPT-4 user, I find myself looking around for other options, just in case GPT-4 becomes unavailable. My personal take on OpenAI GPT-4’s accuracy is definitely high, however the service gets a bit shaky time to time, possibly due to its mainstream popularity.</p><p>The two options I’m looking into are Anthropic’s Claude 2 and Google Vertex AI’s PaLM 2. I primarily use OpenAI’s GPT-4 for conversational basic NLP tasks such as summarization and tagging in Korean, and I intend to utilize Claude 2 and PaLM 2 for similar tasks.</p><h3>Google’s PaLM2</h3><p>PaLM 2 is provided as part of Google Vertex AI’s generative model. It was introduced as a multilingual, reasoning, and coding language model in May 10th, 2023. It comes in variety of sizes so that the model can be versatile in supporting different classes of products.</p><p>With the help of PaLM2, Bard was expanded to new languages. Google Docs and Gmail workspace, med-PaLM2, and sec-PaLM were developed with the advent of PaLM 2.</p><p>Following is a quick start of using text prompts with PaLM2 for Text via Vertex AI : <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/start/quickstarts/quickstart-text">https://cloud.google.com/vertex-ai/docs/generative-ai/start/quickstarts/quickstart-text</a></p><pre>import vertexai<br>from vertexai.language_models import TextGenerationModel<br>from google.oauth2 import service_account<br>from google.auth.transport.requests import Request<br><br>SERVICE_ACCOUNT_KEY_FILE = &#39;service_account_key_file_location/filename.json&#39;<br><br># Create credentials using the service account JSON key file<br>credentials = service_account.Credentials.from_service_account_file(<br>  SERVICE_ACCOUNT_KEY_FILE, scopes=[&quot;https://www.googleapis.com/auth/cloud-platform&quot;])<br><br># Get an access token from the credentials<br>credentials.refresh(Request())<br>access_token = credentials.token<br><br>model = TextGenerationModel.from_pretrained(&quot;text-bison-32k&quot;)<br><br>response = model.predict(<br>        &quot;prompt content goes here&quot;<br>    )<br><br>print(response.text)</pre><p>The pricing of text generation AI on Vertex AI charges by every 1,000 characters of input (prompt) and every 1,000 characters of output (response). Characters are counted by UTF-8 code points and white space is excluded from the count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5eGh0bV6bVeUvwaQH7YGw.png" /></figure><h3>Anthropic’s Claude 2</h3><p>Anthropic values transparency, ethics and taking a cautious approach to advancing AI. The founding members — Dario Amodei and Daniela Amodei were previous members from OpenAI, and Elon Musk was one of the investors.</p><p>The company uses a technique called Constitutional AI — which involves setting constraints on an AI’s behavior during training to align it with human lives. Helpful, Honest, and Harmless (HHH) are three components of the AI models developed at Anthropic.</p><p><strong>Claude 2</strong> is described as a friendly, enthusiastic colleague who can be instructed in natural language. It was released on July 11th, 2023 and is accessible via a user interface (<a href="https://claude.ai/chats">https://claude.ai/chats</a>) or API after registering as a business/enterprise customer. Claude 2 is also available on Google Vertex AI’s marketplace, however I’m still on a wait list, so following is a tutorial provided by Datacamp on how to access Claude 2 API.</p><pre>from anthropic import Anthropic, AsyncAnthropic, HUMAN_PROMPT, AI_PROMPT<br>import os<br><br>anthropic_api_key = os.environ[&quot;ANTHROPIC_API_KEY&quot;]<br><br>anthropic = AsyncAnthropic()<br><br>async def main():<br>    completion = await anthropic.completions.create(<br>        model=&quot;claude-2.1&quot;,<br>        max_tokens_to_sample=300,<br>        prompt=f&quot;{HUMAN_PROMPT}How many moons does Jupiter have?{AI_PROMPT}&quot;,<br>    )<br>    print(completion.completion)<br><br><br>await main()</pre><p>The pricing of Claude charges by every 1,000,000 tokens of input (prompt) and output (response).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9q_IuiIybIzb8lfIgMGbg.png" /></figure><h3>Comparison</h3><p>Comparing the two models with OpenAI’s GPT-4 sums up to the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjBkJCNtzcJHOla6B83Hqg.png" /><figcaption>As of January 2024</figcaption></figure><p>To get a gist of token and character difference, following is a price list of a sampled article based on different token/character counts. GPT-4 classifies as the most expensive, Claude 2 the next, and PaLM 2 as comparatively less costly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzYGjY73fE84y8dPPoIixg.png" /><figcaption>Token and character counts from a sample article — “An Economics Lesson from Tolstoy” By Nick Romeo (translated in Korean via Papago)</figcaption></figure><p>Finally, to measure the performance of different models, I assigned basic summarization, segmentation and tagging tasks.</p><pre>Prompt : <br>&quot;&quot;&quot;<br>Hi, I need to segment a text and summarize each section <br>with a title sentence and three related keywords.<br>Please return output as a python list format only, here&#39;s an example : <br>[{&#39;section_number&#39;: &#39;&#39;, &#39;title&#39;: &#39;&#39;, &#39;keywords&#39;: &#39;&#39;}, ...]<br><br>Following is a sample text :<br>Your diet starts in 37 hours. Synonymous with famous delicacies and culinary legends — Parma ham, Parmesan cheese, Lambrusco wine, the Barilla pasta company, the Alma cooking school — this fetching northern Italian city last year was named a Unesco Creative City for Gastronomy, the first city in Italy to receive the honor. Numerous traditional restaurants and fine-food boutiques assure that no belly goes empty, and on Parma’s outskirts you’ll find museums related to everything from cured pork products to tomatoes. But the city, which was home to talents as diverse as the Renaissance painter Correggio and the 20th-century conductor Arturo Toscanini, also nourishes other appetites — religious, artistic, theatrical, musical, historical — given its wealth of ornate churches and monasteries, an excellent fine-arts museum, and a celebrated theater. Digest it all while pounding the pavement. The compact riverside city is a pleasure to walk. What does the “T” stand for in the name TCafè? Tasteful? The airy, white gallery-like space is certainly that, thanks to a mix of historical details (stone columns, wooden beams) and contemporary cool (design chairs, bubbly electro music).Trendy? The mix of local students and design-media types would suggest it. Or perhaps the “T” is for the Italian word tramonto (sunset), since the outdoor tables are the ideal spot for an end-of-the-day aperitivo while overlooking Parma’s octagonal medieval baptistery. A favorite local flower infuses the Violet Spritz (violet liqueur, prosecco, soda; 6 euros, about $6.60 ), while an Americano (8 euros, or $8.80) caters to classic tastes. All is accompanied (gratis) by another Parma staple, prosciutto. The 19th-century opera composer Giuseppe Verdi was another native of the Parma region, and fall’s Festival Verdi at the gilded 19th-century Teatro Regio is Parma’s annual music gala. The programming during the rest of the year is also impressive, encompassing everything from opera and ballet to jazz and experimental dance. To glimpse the opulent interior — noted for its painted ceiling, tapestry-like curtain, tiers of colonnaded loggias and massive French chandelier — you can take a guided 30-minute tour (5 euros), available mornings and afternoons. Consult the website for times and bookings. Vegans beware: Within the hushed, Old World confines of Cocchi — white tablecloths, oil paintings, patrician crowd — pork is prince and cow is sacred. Sure, you can start with pastas like spaghetti or tortelli, but the cured meats are the stars. Local prosciutto is pungent and soft as tissue, while culatello (a premium variant of prosciutto) is served in ultra thin red-white ribbons of meat and fat that melt like a lozenge on the tongue. Sliced beef in myriad permutations headlines the list of the main courses, along with a robust slab of veal marbled with Parmesan-accented potato purée. Even the marquee dessert — house-made vanilla ice cream — is sliced at your table from a huge chilled slab, just like deli meat. A three-course meal for two costs around 90 euros. Ascetics beware: Those Saturday crowds in Strada Matteo Renato Imbriani, alongside the stone arches of Santissima Annunziata church, aren’t celebrating the joys of temperance. On the contrary. The morning market is an emporium for pleasures of the flesh, notably fresh local fruits, vegetables, jams, juices, butter, cream, grains, wines — and especially ham hocks and cheese blocks. Whether your cold-cut proclivity is for salami, cultatello, prosciutto, gola (made from the pig’s throat) or cicciolata (a blend of nose, ears, back, fat and more), the stand called An.Fo.Ra can sate you. Pair your pork purchases with Parmesan cheese from Araldi, whose slabs and wheels are aged from 24 to 60 months. Swap turf for surf at the new F.I.S.H. restaurant, which opened this year. Simple and cute, the white-tiled space sports raw wood tables and raw wooden planks on the walls. Much of the seafood is raw too, notably the multiple carpaccios and tartares. For variety, the crudo platter includes tender and meaty red shrimp, sweet and smooth langoustine, and more. For those who prefer cooked creatures, the shrimp beignets are crispy outside and mushy-sweet within, thanks to an infusion of béchamel sauce. Even better is the thick branzino, which gets zesty Mediterranean accents from diced tomatoes and olives. Lunch for two costs around 40 euros. Got a ceiling you need painted? Talk to Correggio. That seemed to be the motto around Parma in the early 1500s — at least among religious authorities. In the Camera di San Paolo, part of a Benedictine convent, Correggio adorned the vaulted stone ceiling and walls with trompe l’oeil columns, playful cherubs and the Roman goddess Diana. More powerful, his interior dome of San Giovanni Evangelista church depicts a white-bearded St. John floating in a fiery red sky amid clouds piled with divine onlookers. The Cattedrale di Santa Maria Assunta, which contains Parma’s most highly decorated church interior, also boasts a Correggio cupola. A masterwork of perspective, “Assumption of the Virgin” shows Mary rising skyward through a whirlpool of dense clouds loaded with saints and angels toward a supernova of sun and divine grace.<br>&quot;&quot;&quot; </pre><pre>Prompt (Korean)  : <br>&quot;&quot;&quot;<br>Hi, I need to segment a text and summarize each section <br>with a title sentence and three related keywords.<br>The text will be provided in Korean, therefore title and keywords should be in Korean.<br>Please return output as a python list format only, here&#39;s an example : <br>[{&#39;section_number&#39;: &#39;&#39;, &#39;title&#39;: &#39;&#39;, &#39;keywords&#39;: &#39;&#39;}, ...]<br><br>Following is a sample text :<br>Your diet starts in 37 hours. Synonymous with famous delicacies and culinary legends — Parma ham, Parmesan cheese, Lambrusco wine, the Barilla pasta company, the Alma cooking school — this fetching northern Italian city last year was named a Unesco Creative City for Gastronomy, the first city in Italy to receive the honor. Numerous traditional restaurants and fine-food boutiques assure that no belly goes empty, and on Parma’s outskirts you’ll find museums related to everything from cured pork products to tomatoes. But the city, which was home to talents as diverse as the Renaissance painter Correggio and the 20th-century conductor Arturo Toscanini, also nourishes other appetites — religious, artistic, theatrical, musical, historical — given its wealth of ornate churches and monasteries, an excellent fine-arts museum, and a celebrated theater. Digest it all while pounding the pavement. The compact riverside city is a pleasure to walk. What does the “T” stand for in the name TCafè? Tasteful? The airy, white gallery-like space is certainly that, thanks to a mix of historical details (stone columns, wooden beams) and contemporary cool (design chairs, bubbly electro music).Trendy? The mix of local students and design-media types would suggest it. Or perhaps the “T” is for the Italian word tramonto (sunset), since the outdoor tables are the ideal spot for an end-of-the-day aperitivo while overlooking Parma’s octagonal medieval baptistery. A favorite local flower infuses the Violet Spritz (violet liqueur, prosecco, soda; 6 euros, about $6.60 ), while an Americano (8 euros, or $8.80) caters to classic tastes. All is accompanied (gratis) by another Parma staple, prosciutto. The 19th-century opera composer Giuseppe Verdi was another native of the Parma region, and fall’s Festival Verdi at the gilded 19th-century Teatro Regio is Parma’s annual music gala. The programming during the rest of the year is also impressive, encompassing everything from opera and ballet to jazz and experimental dance. To glimpse the opulent interior — noted for its painted ceiling, tapestry-like curtain, tiers of colonnaded loggias and massive French chandelier — you can take a guided 30-minute tour (5 euros), available mornings and afternoons. Consult the website for times and bookings. Vegans beware: Within the hushed, Old World confines of Cocchi — white tablecloths, oil paintings, patrician crowd — pork is prince and cow is sacred. Sure, you can start with pastas like spaghetti or tortelli, but the cured meats are the stars. Local prosciutto is pungent and soft as tissue, while culatello (a premium variant of prosciutto) is served in ultra thin red-white ribbons of meat and fat that melt like a lozenge on the tongue. Sliced beef in myriad permutations headlines the list of the main courses, along with a robust slab of veal marbled with Parmesan-accented potato purée. Even the marquee dessert — house-made vanilla ice cream — is sliced at your table from a huge chilled slab, just like deli meat. A three-course meal for two costs around 90 euros. Ascetics beware: Those Saturday crowds in Strada Matteo Renato Imbriani, alongside the stone arches of Santissima Annunziata church, aren’t celebrating the joys of temperance. On the contrary. The morning market is an emporium for pleasures of the flesh, notably fresh local fruits, vegetables, jams, juices, butter, cream, grains, wines — and especially ham hocks and cheese blocks. Whether your cold-cut proclivity is for salami, cultatello, prosciutto, gola (made from the pig’s throat) or cicciolata (a blend of nose, ears, back, fat and more), the stand called An.Fo.Ra can sate you. Pair your pork purchases with Parmesan cheese from Araldi, whose slabs and wheels are aged from 24 to 60 months. Swap turf for surf at the new F.I.S.H. restaurant, which opened this year. Simple and cute, the white-tiled space sports raw wood tables and raw wooden planks on the walls. Much of the seafood is raw too, notably the multiple carpaccios and tartares. For variety, the crudo platter includes tender and meaty red shrimp, sweet and smooth langoustine, and more. For those who prefer cooked creatures, the shrimp beignets are crispy outside and mushy-sweet within, thanks to an infusion of béchamel sauce. Even better is the thick branzino, which gets zesty Mediterranean accents from diced tomatoes and olives. Lunch for two costs around 40 euros. Got a ceiling you need painted? Talk to Correggio. That seemed to be the motto around Parma in the early 1500s — at least among religious authorities. In the Camera di San Paolo, part of a Benedictine convent, Correggio adorned the vaulted stone ceiling and walls with trompe l’oeil columns, playful cherubs and the Roman goddess Diana. More powerful, his interior dome of San Giovanni Evangelista church depicts a white-bearded St. John floating in a fiery red sky amid clouds piled with divine onlookers. The Cattedrale di Santa Maria Assunta, which contains Parma’s most highly decorated church interior, also boasts a Correggio cupola. A masterwork of perspective, “Assumption of the Virgin” shows Mary rising skyward through a whirlpool of dense clouds loaded with saints and angels toward a supernova of sun and divine grace.<br>&quot;&quot;&quot;</pre><p>Following table includes the segmentation results from sample of NYT article — “36 hours in Parma” (English &amp; Korean) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wa_Lr9sC1uSyec-0zZ-C2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTllw_d4AFGe3HPc-jkomA.png" /></figure><p>Overall, Claude2 provides a natural title in a sentence format with intuitive keywords whereas GPT-4 provides a title phrase with specific keywords. PaLM2 on the other hand, shows a bit unsatisfactory result in Korean.</p><p>The preference of the results may vary between the users, but personally Claude 2 met all my criteria.</p><p>My goal was to measure the speed of the API as well, however will create another post when Claude 2 API is approved.</p><p>Thanks for reading! :)</p><h3>References</h3><ul><li><a href="https://blog.google/technology/ai/google-palm-2-ai-large-language-model/">https://blog.google/technology/ai/google-palm-2-ai-large-language-model/</a></li><li><a href="https://cloud.google.com/vertex-ai/docs/generative-ai/pricing">https://cloud.google.com/vertex-ai/docs/generative-ai/pricing</a></li><li><a href="https://www.anthropic.com/news/claude-2">https://www.anthropic.com/news/claude-2</a></li><li><a href="https://www.datacamp.com/tutorial/getting-started-with-the-claude-2-and-the-claude-2-api">https://www.datacamp.com/tutorial/getting-started-with-the-claude-2-and-the-claude-2-api</a></li><li><a href="https://textcortex.com/ko/post/claude-2-vs-palm-2#3">https://textcortex.com/ko/post/claude-2-vs-palm-2#3</a></li><li><a href="https://www.nytimes.com/interactive/2016/07/21/travel/what-to-do-36-hours-parma-italy.html">https://www.nytimes.com/interactive/2016/07/21/travel/what-to-do-36-hours-parma-italy.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb05422a5a43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Multimodal Learning]]></title>
            <link>https://medium.com/@hannah.hj.do/introduction-to-multimodal-learning-3226ed49d577?source=rss-5b0dc3517e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/3226ed49d577</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[sound]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[text]]></category>
            <dc:creator><![CDATA[Hannah Do]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 01:59:10 GMT</pubDate>
            <atom:updated>2023-12-16T01:59:10.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*6H5MjFhkzxacUIcT" /><figcaption>What is Multimodal Learning? (madcapsoftware)</figcaption></figure><h3>Definition of Multimodal Learning</h3><p>Multimodal learning involves the simultaneous use of various teaching methods by the educator or presenter. According to findings from the Gordon Kelley Academic Success Center, students exposed to multiple learning styles tend to understand the material more quickly, retaining a more information throughout the learning process.</p><p>The VARK model is one of the popular method created by Neil Fleming to explain the different types of learners :</p><ol><li>Visual</li><li>Auditory</li><li>Reading/Writing</li><li>Kinesthetic</li></ol><h3>Multimodal Learning for Computers</h3><p>Human learning often involves the integration of multiple sensory inputs to gain knowledge or address a problem. Intuitively, it is conceivable that Deep Learning models can emulate this by processing various modalities such as audio, image, text, and sensory data.</p><p>Problem is that each type of data comes with different data structures and characteristics. For instance, an image dataset may be represented as a 2D/3D vector, while text data might be expressed as an embedding vector. Additionally, depending on the training approach, deep learning models may exhibit a bias towards one modality, as they might prioritize a more straightforward path.</p><p>Despite these complexities, leveraging multi-modal learning is crucial because of its ability to tackle novel challenges that may be inaccessible through single-modal approaches.</p><h3>Three different strategies for multi-modal learning</h3><p><strong>A. Matching :</strong></p><ul><li>Matching the data types to a common feature space for training</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*_8WrjFI3VTUyImss0kuVbg.png" /></figure><ul><li>Here, text is converted to a feature space using models such as Word2Vec. And images are tagged with words using CV models. Training the ‘joint embedding space’ results in finding similarities between the images via text.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9B4u6QjkjU0O-Rk9oLX9w.png" /><figcaption>Audio &amp; Sound joint embedding (sound tagging)</figcaption></figure><p><strong>B. Cross modal translation :</strong></p><ul><li>Translating one form of modality to another</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WujpmaWDUbDFwRKJQGkQgA.png" /><figcaption>Creating text description of an image (CNN + RNN)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1PuGssseGFGBKi-_fvPpA.png" /><figcaption>Creating images from a text (generative model : generator + discriminator)</figcaption></figure><p><strong>C. Cross Modal Reasoning :</strong></p><p>Referencing a characteristic of one modality when producing a result from another modality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YM6wnSaU4cR84lEyZOr5g.png" /><figcaption>Waveform (1D signal) -&gt; Power spectrum -&gt; Spectogram (acoustic feature)</figcaption></figure><ul><li>In order to use the waveform in machine learning, it is converted to an acoustic feature with Fourier Transform.</li></ul><p>In conclusion, multi-modal learning is like a versatile toolbox with endless applications across different areas. Bringing together various sensory inputs not only makes learning more engaging but also opens doors to creative solutions for challenges that traditional, single-modal approaches might find tricky to tackle.</p><ul><li>Speech2Face : Using voice data to generate a person’s face</li><li>Sound source localization : Predicting the location of the sound extracted from a video</li><li>Video-to-text : Predicting the next dialogues in a video clip</li></ul><h3>References</h3><ol><li><a href="https://www.madcapsoftware.com/blog/what-is-multimodal-learning/">https://www.madcapsoftware.com/blog/what-is-multimodal-learning/</a></li><li><a href="https://velog.io/@ysw2946/9.-Multi-modal-Learning">https://velog.io/@ysw2946/9.-Multi-modal-Learning</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3226ed49d577" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>