<?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 Saskia Dwi Ulfah on Medium]]></title>
        <description><![CDATA[Stories by Saskia Dwi Ulfah on Medium]]></description>
        <link>https://medium.com/@sdwiulfah?source=rss-3863a0821232------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*crQjZ7EVU2GUQLI7OgB6zA.png</url>
            <title>Stories by Saskia Dwi Ulfah on Medium</title>
            <link>https://medium.com/@sdwiulfah?source=rss-3863a0821232------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:36:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdwiulfah/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[Attention for Du]]></title>
            <link>https://medium.com/@sdwiulfah/attention-for-du-686b9186a0cc?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/686b9186a0cc</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 02:27:50 GMT</pubDate>
            <atom:updated>2024-02-18T15:27:15.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Attention for Dummies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHQqxTdhX2t3PUWepTa3MQ.jpeg" /></figure><p>OpenAI’s GPT-4 has become a breakthrough in the world of natural language modeling. What makes them awesome relies on something called transformers. In this article, we will go through the foundation of the transformers architecture: the self-attention mechanism.</p><h3><strong>The Rise of Transformers Architecture</strong></h3><p>Before exploring the unique aspects of transformer architecture, let’s understand why it has become popular.</p><p>Recurrent neural network (RNN), long short-term memory (LSTM), and gated recurrent unit (GRU) were previously the go-to choices for sequence modeling and were considered state-of-the-art due to their recurrent nature. This characteristic enables those recurrent networks to capture the dependencies by processing data one piece at a time sequentially.</p><p>These sequential workflows have three major drawbacks: computational inefficiency, time inefficiency, and limited memory for long sequences. The inability to process long sequences impedes recurrent models from capturing meaningful information, ultimately degrading performance.</p><p>The attention mechanisms have been employed alongside recurrent networks to address these issues. However, the fundamental limitation remains the sequential processing. Transformers, through the self-attention mechanism, aim to resolve this problem by relying solely on the attention mechanism, thereby enabling parallelization.</p><h3><strong>The Architecture Breakdown</strong></h3><p>I’m sure that when you look for articles to learn about transformer architecture, most of them will show the famous image from the “<a href="https://arxiv.org/pdf/1706.03762.pdf">Attention is All You Need</a>” paper by Vaswani et al. In this article, I will merely discuss how the data traverses this network architecture. That is, I am going to take it step-by-step and zoom in on each part of the network instead of explaining the global picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*CxI9UPeSGmuxRV7SEEVhng.png" /><figcaption>Transformer Architecture (source: <a href="https://arxiv.org/pdf/1706.03762.pdf">Attention is All You Need</a>)</figcaption></figure><h4>The Encoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*k6U8jdNA2qiDJUU9fDcIoA.png" /><figcaption>The Encoder of Transformer</figcaption></figure><p>Okay, let’s first focus on the encoder part. If you look at the picture above, the grey box is what makes up the encoder (from now on, we’ll call each box a “layer”). In the original paper, the encoder is made up of 6 identical grey layers (N = 6).</p><p>In each grey layer, there are two sub-layers: multi-head self attention ( the orange one) and position-wise fully connected feed-forward network (the blue one). Let’s find out what each one does and produces!</p><p><strong>Input Embedding and Positional Encoding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*7zLH2-T4yMoBGhWwuPtc9w.png" /><figcaption>Input Embedding and Positional Encoding</figcaption></figure><p>Before we feed a sentence into the transformer, the transformer doesn’t directly process the sentence. Instead, it first converts the sentence into numbers, known as word embeddings.</p><p>For instance, take the sentence “a beautiful lady”. Each word in this sentence gets its own vector (a list of numbers). The size of this vector depends on the embedding size. In this paper, the author suggests using an embedding size of 512. So, for “a beautiful lady,” we get a numerical representation that is 3 vectors long (think as a matrix row), each 512 numbers long (think as a matrix column), making it a 3x512 numerical representation.</p><p>Due to the presence of recurrence, the transformer preserves order through positional encoding. Simply put, positional encoding provides context about the order in the sentence. As we may know, in terms of text data, the word order can imply different meanings.</p><p>The process of positional encoding involves adding a matrix of the same size as the input embedding to the input embedding itself. Extending our previous example of “a beautiful lady,” up until now, this sentence has been represented by a 3x512 matrix containing word and context representation.</p><p><strong>Multi-Head Self Attention</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*qmVrOZfTG-R_Son9lb1Xcg.png" /><figcaption>Multi-Head Self Attention</figcaption></figure><p>“Multi” refers to the condition where the occurrences are more than 2. As the name might suggest, each encoder layer may consist of multiple self-attention layers. In the paper itself, it was mentioned that there is the use of 8 self-attention layers per encoder layer.</p><p>Ok, let’s understand the computation process that occurs in each individual self-attention layer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*z7WNwg7xZ1WuxIjcZ70W7Q.png" /><figcaption>The Computation in Each Self-Attention Layer (Graphically)</figcaption></figure><p>Pay attention to the image above! We have several new terms/vectors here: Q, K, V. These vectors correspond to query, key, and values, respectively. What are each of them, actually?</p><p>In the process of understanding queries, keys, and values, I will start from the perspective of matrix operations. One thing we should keep in mind is that queries, keys, and values are derived from our previous input matrix, which has a shape of (3 , 512). It’s important to remember that the input to the self-attention layer is the sum of the input embedding and its positional encoding. From this perspective, we can conceptualize it as follows:</p><ul><li>Query = [Input matrix] x [matrix a].</li><li>Key = [Input matrix] x [matrix b].</li><li>Value = [Input matrix] x [matrix c].</li></ul><p>Based on this, we are quite certain that [matrix a], [matrix b], and [matrix c] have dimensions of (512 , a certain number). The original paper specifies that ‘a certain number’ is equal to 64. Hence, their dimensions are (512 , 64).</p><ul><li>Shape of query = (3, 512) x (512, 64) = (3, 64).</li><li>Shape of key = (3, 512) x (512, 64) = (3, 64).</li><li>Shape of value = (3, 512) x (512, 64) = (3, 64).</li></ul><p>Okay, now we have their vector dimensions. But, what are the three of them actually?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*_ymPsJ7eUZJP5ZK4ifDEHw.png" /><figcaption>The Computation in Each Self-Attention Layer (Mathematically)</figcaption></figure><p>If we look back at the animation showing how Q, K, and V relate, we will end up with the above equation mathematically. Let’s first understand what happens inside the softmax function:</p><ul><li>We multiply the Q and K matrices, which gives us a (3, 3) matrix. This matrix is then scaled down by a certain factor before we apply the softmax function.</li><li>So far, we still have a (3, 3) matrix. Remember at the beginning, we talked about having 3 words in the phrase “a beautiful lady”. Now, this (3, 3) matrix shows how much each word affects the others. For example, in the first row of the matrix, it shows how the word “a” relates to “a”, “beautiful”, and “lady”.</li></ul><h4>The Decoder</h4><h3>Conclusion</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686b9186a0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brain MRI Segmentation with Segment Anything Model (SAM) Part 2: Modeling — Conclusion]]></title>
            <link>https://medium.com/@sdwiulfah/brain-mri-segmentation-with-segment-anything-model-sam-part-2-modeling-conclusion-61393308f803?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/61393308f803</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 17:37:24 GMT</pubDate>
            <atom:updated>2024-01-03T17:59:34.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Brain MRI Segmentation with Segment Anything Model (SAM) Part 2: Modeling — Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4HnEqEELbQihzYsz6lxLQ.png" /><figcaption>Brain MRI (source: <a href="https://newatlas.com/biology/mri-study-charts-brain-changes-from-birth-to-death/">newatlas.com</a>)</figcaption></figure><blockquote>The implementation code can be found in Github or Kaggle.</blockquote><ul><li><a href="https://github.com/saskia-dwi-ulfah/sam_for_brain_MRI_segmentation">GitHub - saskia-dwi-ulfah/sam_for_brain_MRI_segmentation</a></li><li><a href="https://www.kaggle.com/code/saskiadwiulfah18/segment-anything-model-for-brain-mri-segmentation?kernelSessionId=155363687">Segment Anything Model for Brain MRI Segmentation</a></li></ul><blockquote><a href="https://medium.com/@sdwiulfah/brain-mri-segmentation-with-segment-anything-model-sam-16d0b4101a85">Click here</a> to the part 1 of this article.</blockquote><h3>6. Modeling</h3><p>Having our dataset proper, we are now ready to put our data to SAM.</p><h4>Model Checkpoint and Frozen Layers</h4><p>Firstly, we need to download the model checkpoint.</p><pre># download model checkpoint from HuggingFace<br>model = SamModel.from_pretrained(&quot;facebook/sam-vit-base&quot;)</pre><p>It’s important to note that our model is composed of three main components: the image encoder, the prompt encoder, and the mask decoder. In our approach, we focus on retraining only the mask decoder part, while keeping the weights of the other parts frozen. This strategy is chosen due to the relative ease of training the mask decoder. As highlighted in the original paper, the mask decoder is the most lightweight component of the model, making it more adaptable and less resource-intensive to train compared to the other parts.</p><pre># make sure we only compute gradients for mask decoder<br>for name, param in model.named_parameters():<br>  if name.startswith(&quot;vision_encoder&quot;) or name.startswith(&quot;prompt_encoder&quot;):<br>    param.requires_grad_(False)</pre><h4>Loss and Optimizer</h4><p>Before initiating the training process, it’s crucial to define both an optimizer and a loss function, as the goal of training is to minimize this loss function. For our project, we will use FocalLoss from monai.losses. Focal Loss is commonly employed in image segmentation tasks, especially when there’s a class imbalance in the dataset.</p><p>To conceptualize image segmentation, we can think of it as a pixel-level classification problem. In our case, we have two classes: 0 represents pixels of normal tissue, and 1 represents pixels of cancerous tissue. Upon examining our dataset, it becomes evident that pixels labeled as 1 (cancerous) are significantly fewer than those labeled as 0 (normal), indicating a clear class imbalance. Focal Loss is particularly effective in such scenarios as it helps to focus more on the less frequent, but often more critical, class in the dataset.</p><p>The optimizer is an algorithm used to optimize the neural network, aiming to achieve the minimum possible loss value. A frequently utilized optimizer is Adam from torch.optim. For our purposes, we have set the learning rate to 0.001.</p><pre># lr = 10e-3<br>optimizer = Adam(model.mask_decoder.parameters(), lr=CFG.LEARNING_RATE)<br>seg_loss = monai.losses.FocalLoss(reduction=&#39;mean&#39;)</pre><h4>Training Loop and Evaluation</h4><p>Finally, we are ready to implement the code for the training loop.</p><pre>num_epochs = CFG.EPOCH<br>device = CFG.DEVICE<br><br># put the model to the available device <br>model.to(device)<br># training mode<br>model.train()<br><br>epoch_losses = []<br>epoch_ious = []<br><br>for epoch in range(num_epochs):<br>    print(f&#39;EPOCH: {epoch}&#39;)<br>    # save losses in every batch<br>    batch_losses = []<br>    # save IoU in every batch<br>    batch_ious = []<br><br>    for i, batch in enumerate(tqdm(train_dataloader)):<br><br>      # forward pass<br>      outputs = model(pixel_values=batch[&quot;pixel_values&quot;].to(device),<br>                      input_boxes=batch[&quot;input_boxes&quot;].to(device),<br>                      multimask_output=False)<br><br>      # process the output: from sigmoid to class<br>      predicted_masks = outputs.pred_masks.squeeze(1) <br>      ground_truth_masks = batch[&quot;ground_truth_mask&quot;].float().to(device)<br><br>      sam_masks_prob = torch.sigmoid(predicted_masks)<br>      sam_masks_prob = sam_masks_prob.squeeze()<br>      sam_masks = (sam_masks_prob &gt; 0.5)<br><br>      # compute loss<br>      loss = seg_loss(predicted_masks, ground_truth_masks.unsqueeze(1))<br>      batch_losses.append(loss.item())<br><br>      # compute IoU: return 2 values: 1 for each batch<br>      ious = compute_iou(sam_masks.unsqueeze(1),<br>                        ground_truth_masks.unsqueeze(1), ignore_empty=False)<br>      batch_ious.append(ious.mean())<br><br>      &#39;&#39;&#39;<br>      clear_output(wait=True)<br><br>      fig, axs = plt.subplots(1, 3)<br>      xmin, ymin, xmax, ymax = get_bounding_box(batch[&#39;ground_truth_mask&#39;][0])<br>      rect = patches.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, linewidth=1, edgecolor=&#39;r&#39;, facecolor=&#39;none&#39;)<br><br>      axs[0].set_title(&#39;Input Image&#39;)<br>      axs[0].imshow(batch[&quot;pixel_values&quot;][0,1], cmap=&#39;gray&#39;)<br>      axs[0].axis(&#39;off&#39;)<br><br>      axs[1].set_title(&#39;Actual Mask&#39;)<br>      axs[1].imshow(batch[&#39;ground_truth_mask&#39;][0], cmap=&#39;copper&#39;)<br>      axs[1].add_patch(rect)<br>      axs[1].axis(&#39;off&#39;)<br><br>      # apply sigmoid<br>      medsam_seg_prob = torch.sigmoid(outputs.pred_masks[0].squeeze(1))<br><br>      # convert soft mask to hard mask<br>      medsam_seg_prob = medsam_seg_prob.detach().cpu().numpy().squeeze()<br>      medsam_seg = (medsam_seg_prob &gt; 0.5).astype(np.uint8)<br><br>      axs[2].set_title(&#39;Predicted Mask&#39;)<br>      # axs[2].imshow(predicted_masks[0].cpu().detach().numpy().reshape(256,256,1)*255, cmap=&#39;copper&#39;)<br>      axs[2].imshow(medsam_seg, cmap=&#39;copper&#39;)<br>      axs[2].axis(&#39;off&#39;)<br><br>      plt.tight_layout()<br>      plt.show()<br>      &#39;&#39;&#39;<br><br>      # backward pass (compute gradients of parameters w.r.t. loss)<br>      optimizer.zero_grad()<br>      loss.backward()<br><br>      # optimize<br>      optimizer.step()<br><br>      if torch.cuda.is_available():<br>        torch.cuda.empty_cache()<br><br>    # compute mean loss for an epoch<br>    mean_loss = mean(batch_losses)<br>    epoch_losses.append(mean_loss)<br>    print(f&#39;Mean loss: {mean_loss}&#39;)<br><br>    # compute mean IoU for an epoch<br>    mean_iou = mean([t.cpu().item() for t in batch_ious])<br>    epoch_ious.append(mean_iou)<br>    print(f&#39;Mean IoU: {mean_iou}&#39;)<br><br># for each batch: the IoU is the average of 2 IoUs (there are 2 batch sizes)<br># for each epoch: the average of the IoU for each batch</pre><p>We will train our model for 10 epochs, during which we will calculate the mean loss and mean IoU (Intersection over Union) for each epoch. At the end of the training process, we will plot these metrics for analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6StPFEFr9KTitGDYZHn53w.png" /><figcaption>Intersection over union (Source: <a href="https://www.v7labs.com/blog/intersection-over-union-guide">www.v7labs.com</a>)</figcaption></figure><p>IoU is a crucial metric in image segmentation tasks. It measures the degree of overlap between the predicted mask and the ground truth mask. IoU scores span from 0 to 1, where 0 denotes no overlap and 1 indicates complete overlap.</p><p><strong>PROCESS IN EACH EPOCH</strong></p><p>During each epoch, we will calculate the loss and IoU for every iteration. In each iteration, the network processes two data points. We will then generate a mask prediction based on the MRI image and its corresponding prompt. This prediction allows us to compute the iteration’s loss.</p><p>For IoU calculation, we further process the model’s output. To determine the corresponding probabilities, we apply the sigmoid function. A probability greater than 0.5 will classify the pixel as 1, and below 0.5 as 0. This entire process constitutes forward propagation, where data moves from the input layer to the output layer.</p><p>The subsequent phase is backward propagation. In this stage, we propagate the information from the output layer back to the input layer, updating the network’s weights accordingly.</p><p>At the conclusion of each epoch, we will calculate the average loss and the average IoU, aggregating the results from all iterations within that epoch. This process helps in assessing the model’s performance and guiding its improvement over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*qZ-6-J6kJe2YZJ5O2SFGNw.png" /><figcaption>Training process</figcaption></figure><p>The commented section of the code is designed to plot the first image of the two images processed in each iteration. This plotting is useful for monitoring the model’s performance as the number of iterations increases, providing insights into how the model’s ability evolves during training. However, in this project, we’ve opted not to use this part of the code in order to avoid memory issues that could hinder the rendering of other primary results. This decision helps ensure smooth execution and focuses resources on the most critical aspects of the project.</p><h4>Training Metrics Plot</h4><p>After completing the 10th epoch, we will have a set of 10 values for both loss and IoU. We will then visualize these values by plotting them using the provided code. This graphical representation will help in understanding the model’s performance and progression over the course of the 10 epochs.</p><pre># plot loss<br>plt.plot(np.arange(1,CFG.EPOCH+1), epoch_losses)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.ylabel(&#39;Loss&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*MGSld-zoF1RvyPuyLSKa5A.png" /><figcaption>Training loss</figcaption></figure><pre># plot IoU<br>plt.plot(np.arange(1,CFG.EPOCH+1), epoch_ious)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.ylabel(&#39;IoU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*R-BmrLRAqbWAOEShjXWDqA.png" /><figcaption>Training IoU</figcaption></figure><p>In the medical imaging context, the model’s convergence at an IoU of 0.65 and a peak IoU of 0.67 is noteworthy, indicating a reliable capability in identifying cancerous tissues in MRI scans. However, the critical nature of medical diagnoses necessitates even higher accuracy. Future enhancements might include using more diverse datasets, advanced image augmentation, and incorporating medical expertise into the training process to bolster the model’s precision and applicability in clinical settings.</p><h3>7. Inference</h3><h4><strong>Inference with Test Dataset using DataLoader</strong></h4><p>Initially, we divided our data into training and testing sets. Similarly to the training set, we define SAMDataset and DataLoader for the testing set. The key difference is setting batch_size = 1, allowing us to closely monitor predictions for individual images one at a time.</p><pre># create test_dataloader<br>test_sam_ds = SAMDataset(test_dataset, processor=processor)<br>test_dataloader = DataLoader(test_sam_ds, batch_size=CFG.TEST_BATCH_SIZE, shuffle=False)</pre><p>Similar to the training phase, we establish a testing loop to iterate over the dataset and output the resulting predictions. However, during this phase, we set our model to evaluation mode to ensure accurate performance assessment without the influence of factors like dropout or batch normalization that are typically active during training.</p><pre>test_ious = []<br># evaluation mode<br>model.eval()<br><br># iteratire through test images<br>with torch.no_grad():<br>    for batch in tqdm(test_dataloader):<br><br>        # forward pass<br>        outputs = model(pixel_values=batch[&quot;pixel_values&quot;].cuda(),<br>                      input_boxes=batch[&quot;input_boxes&quot;].cuda(),<br>                      multimask_output=False)<br><br>        ground_truth_masks = batch[&quot;ground_truth_mask&quot;].float().cuda()<br><br>        # apply sigmoid<br>        sam_mask_prob = torch.sigmoid(outputs.pred_masks.squeeze(1))<br>        sam_mask_prob = sam_mask_prob.cpu().numpy().squeeze()<br>        sam_mask = (sam_mask_prob &gt; 0.5)<br><br>        iou = compute_iou(torch.from_numpy(sam_mask).reshape(1, 256, 256).unsqueeze(1).cpu(),<br>                          ground_truth_masks.unsqueeze(1).cpu(), ignore_empty=False)<br><br>        print(f&#39;IoU: {iou}&#39;)<br>        test_ious.append(iou)<br>        <br>        # plot the MRI image<br>        plt.figure(figsize=(12,4))<br>        plt.subplot(1,3,1)<br>        plt.imshow(batch[&quot;pixel_values&quot;][0,1], cmap=&#39;gray&#39;)<br>        plt.title(&#39;MRI Image&#39;)<br>        plt.axis(&#39;off&#39;)<br>        <br>        # plot the ground truth mask<br>        plt.subplot(1,3,2)<br>        plt.imshow(batch[&quot;ground_truth_mask&quot;][0], cmap=&#39;copper&#39;)<br>        plt.title(&#39;Actual Mask&#39;)<br>        plt.axis(&#39;off&#39;)<br>        <br>        # plot the predicted mask<br>        plt.subplot(1,3,3)<br>        plt.imshow(sam_mask, cmap=&#39;copper&#39;)<br>        plt.title(&#39;Predicted Mask&#39;)<br>        plt.axis(&#39;off&#39;)<br>        <br>        plt.tight_layout()<br>        plt.show()</pre><p>After running the code, you’ll see a preview of the expected output. For a comprehensive view of the results on the testing dataset, please visit the specified <a href="https://github.com/saskia-dwi-ulfah/sam_for_brain_MRI_segmentation">Github repository</a> or <a href="https://www.kaggle.com/code/saskiadwiulfah18/segment-anything-model-for-brain-mri-segmentation?scriptVersionId=155363687">Kaggle kernel</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*m6rQf_dTuSBt47eyUwscSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*wjyaKpZgRm-yzprusSxVfQ.png" /><figcaption>Prediction for testing set</figcaption></figure><p>Observing the output closely reveals a pattern where the mo del achieves a good IoU for cases where the cancerous area is obvious and well-defined. Conversely, when the cancerous tissue is small, resulting in fewer white pixels in the ground truth mask, SAM tends to predict only a minimal affected area or, in some instances, fails to detect any anomaly, predicting an all-black pixel mask. This suggests that while the model is effective in identifying clear cases of cancerous tissues, its performance diminishes with smaller, less conspicuous areas. It highlights the need for further model refinement, especially in enhancing its sensitivity to detect smaller cancerous regions, which is crucial for early and accurate medical diagnoses.</p><h4>Inference with a New, Unseen Dataset</h4><p>Ideally, with a well-trained machine learning model, we expect it to output predictions given an input image. However, in the case of a model that bases its predictions on an inputted prompt, what happens if we have a new MRI image without a ground truth mask to extract the bounding box from? Well, we can find an alternative way to provide the prompt.</p><p><strong>Prompt 1: Grid of Points</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*QnF1Z8nLXEtfQv1u.jpg" /><figcaption>10x10 grid image (Source: <a href="https://id.pinterest.com/pin/85779567889935419/">www.pinterest.com</a>)</figcaption></figure><p>The first prompt we aim to explore is a set of points for constructing a grid. We provide a set of points to serve as a grid partitioning our data. In this instance, we will use a 10x10 grid with 100 pairs of (x,y) coordinates. SAM expects this set of points to be shaped as (batch size, point batch size, number of points per image, 2):</p><ul><li>Batch size corresponds to the number of images we plan to process at a time; here, we aim to predict a single image.</li><li>Point batch size corresponds to the number of point sets we have. Point batch size also determines how many masks to be generated. In this case, we have only one set of points. One mask to be generated.</li><li>Number of points per image indicates the number of points present in each set. With a 10x10 grid, we have 100 points in point set.</li><li>2 represents the (x, y) value pair needed to construct a point.</li></ul><pre>&quot;&quot;&quot;<br>input_points (torch.FloatTensor of shape (batch_size, num_points, 2)) —<br>Input 2D spatial points, this is used by the prompt encoder to encode the prompt.<br>The points can be obtained by passing a list of list of list to the processor that will create corresponding torch tensors<br>of dimension 4. The first dimension is the image batch size, the second dimension<br>is the point batch size (i.e. how many segmentation masks do we want the model to<br>predict per input point), the third dimension is the number of points per segmentation<br>mask (it is possible to pass multiple points for a single mask), and the last dimension<br>is the x (vertical) and y (horizontal) coordinates of the point. If a different number<br>of points is passed either for each image, or for each mask, the processor will create<br>“PAD” points that will correspond to the (0, 0) coordinate, and the computation of the<br>embedding will be skipped for these points using the labels.<br>&quot;&quot;&quot;<br><br># define the size of your array (the size of image)<br>array_size = 256<br><br># define the size of your grid: 10x10 grid<br>grid_size = 10<br><br># generate the grid points<br>x = np.linspace(0, array_size-1, grid_size)<br>y = np.linspace(0, array_size-1, grid_size)<br><br># generate a grid of coordinates<br>xv, yv = np.meshgrid(x, y)<br><br># convert the numpy arrays to lists<br>xv_list = xv.tolist()<br>yv_list = yv.tolist()<br><br># combine the x and y coordinates into a list of list of lists<br>input_points = [[[int(x), int(y)] for x, y in zip(x_row, y_row)] for x_row, y_row in zip(xv_list, yv_list)]<br><br># we need to reshape our nxn grid to the expected shape of the input_points tensor<br># (batch_size, point_batch_size, num_points_per_image, 2),<br># where the last dimension of 2 represents the x and y coordinates of each point.<br># batch_size: The number of images you&#39;re processing at once.<br># point_batch_size: The number of point sets you have for each image.<br># num_points_per_image: The number of points in each set.<br>input_points = torch.tensor(input_points).view(1, 1, grid_size*grid_size, 2)</pre><p>Let’s make a prediction using a set of points as a prompt.</p><pre># take random image<br>image = test_dataset[-1][&quot;image&quot;]<br>ground_truth_mask = np.array(test_dataset[-1][&quot;mask&quot;])<br><br># prepare image + box prompt for the model<br>inputs = processor(image, input_points=input_points, return_tensors=&quot;pt&quot;).to(device)<br><br># make prediction<br>model.eval()<br><br># forward pass<br>with torch.no_grad():<br>  outputs = model(**inputs, multimask_output=False)<br><br># apply sigmoid<br>medsam_seg_prob = torch.sigmoid(outputs.pred_masks.squeeze(1))<br>medsam_seg_prob = medsam_seg_prob.cpu().numpy().squeeze()<br>medsam_seg = (medsam_seg_prob &gt; 0.5)</pre><pre><br><br>fig, axes = plt.subplots(1, 3, figsize=(15, 5))<br><br># plot the first image on the left<br>axes[0].imshow(np.array(image), cmap=&#39;gray&#39;)  # assuming the first image is grayscale<br>axes[0].set_title(&quot;Image&quot;)<br><br># plot the second image on the right<br>axes[1].imshow(ground_truth_mask)  # assuming the second image is grayscale<br>axes[1].set_title(&quot;Actual Mask&quot;)<br><br># plot the second image on the right<br>axes[2].imshow(medsam_seg, cmap=&#39;gray&#39;)  # assuming the second image is grayscale<br>axes[2].set_title(&quot;Prediction&quot;)<br><br># hide axis ticks and labels<br>for ax in axes:<br>    ax.set_xticks([])<br>    ax.set_yticks([])<br>    ax.set_xticklabels([])<br>    ax.set_yticklabels([])<br><br># display the images side by side<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*CS0qchr9EYPnz8kT5xHJWQ.png" /><figcaption>Prediction with set of points as a prompt</figcaption></figure><p>Let’s compute the IoU.</p><pre>pred = torch.from_numpy(medsam_seg).float()<br>act = torch.from_numpy(ground_truth_mask).float()<br>iou = compute_iou(act/255, pred, ignore_empty=False)</pre><p>When executing the code, we obtain an IoU of 0.0070. This low IoU value indicates that the model’s prediction has minimal overlap with the ground truth, suggesting that the model’s performance with this particular prompt configuration is not optimal. This result underscores the need for further tuning or exploration of different prompt strategies to enhance the model’s accuracy in segmenting images, especially in complex scenarios like medical image analysis.</p><p><strong>Prompt 2: Bounding Box around Brain Contour</strong></p><p>This time, we will employ a bounding box approach again, but with a focus on encompassing the brain’s contour. The code provided will generate a rectangle around the brain and output the position of this bounding box.</p><pre># function to draw a bounding box around the object in an image<br><br>def draw_bounding_box(image):<br><br>    # convert the image to grayscale<br>    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br><br>    # apply a blur to the image to reduce noise<br>    blurred = cv2.GaussianBlur(gray, (5, 5), 0)<br><br>    # threshold the image to get the object in binary<br>    _, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)<br><br>    # find contours in the thresholded image<br>    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)<br><br>    # find the largest contour, assuming the object to bound is the largest one<br>    largest_contour = max(contours, key=cv2.contourArea)<br><br>    # draw a bounding box around the largest contour<br>    x, y, w, h = cv2.boundingRect(largest_contour)<br>    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)<br><br>    # display the image<br>    plt.imshow(image)<br><br>    # extract the bounding box location<br>    x_min = x<br>    x_max = x + w<br>    y_min = y<br>    y_max = y + h<br><br>    return [x_min, y_min, x_max, y_max]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*w8XcFHvCYwGVq-FQPiN1UQ.png" /><figcaption>Bounding box around brain contour</figcaption></figure><p>For the remaining steps, we follow the same procedure as when using a set of points as a prompt.</p><pre>image = test_dataset[10][&quot;image&quot;]<br>ground_truth_mask = np.array(test_dataset[10][&quot;mask&quot;])<br><br># prepare image + box prompt for the model<br>inputs = processor(image, input_boxes=[[pr]], return_tensors=&quot;pt&quot;).to(device)<br><br>model.eval()<br><br># forward pass<br>with torch.no_grad():<br>  outputs = model(**inputs, multimask_output=False)<br><br># apply sigmoid<br>medsam_seg_prob = torch.sigmoid(outputs.pred_masks.squeeze(1))<br>medsam_seg_prob = medsam_seg_prob.cpu().numpy().squeeze()<br>medsam_seg = (medsam_seg_prob &gt; 0.5)</pre><pre>fig, axes = plt.subplots(1, 3, figsize=(15, 5))<br><br># plot the first image on the left<br>axes[0].imshow(np.array(image), cmap=&#39;gray&#39;)  # assuming the first image is grayscale<br>axes[0].set_title(&quot;Image&quot;)<br><br># plot the second image on the right<br>axes[1].imshow(ground_truth_mask)  # assuming the second image is grayscale<br>axes[1].set_title(&quot;Actual Mask&quot;)<br><br># plot the second image on the right<br>axes[2].imshow(medsam_seg, cmap=&#39;gray&#39;)  # assuming the second image is grayscale<br>axes[2].set_title(&quot;Prediction&quot;)<br><br># hide axis ticks and labels<br>for ax in axes:<br>    ax.set_xticks([])<br>    ax.set_yticks([])<br>    ax.set_xticklabels([])<br>    ax.set_yticklabels([])<br><br># display the images side by side<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*hy03rrHWCYCYUWmEjiJSQA.png" /><figcaption>Prediction with bounding box around the brain as a prompt</figcaption></figure><p>Let’s compute the IoU.</p><pre>pred = torch.from_numpy(medsam_seg).float()<br>act = torch.from_numpy(ground_truth_mask).float()<br>iou = compute_iou(act/255, pred, ignore_empty=False)</pre><p>We achieved an IoU value of 0.2866. While this is an improvement compared to using a set of points as a prompt, it still falls short of our expectations. This outcome suggests that while the bounding box around the brain contour provides a better guide for the model, further adjustments or different approaches may be necessary to meet the desired accuracy levels in our segmentation tasks.</p><h3>8. SAM vs Typical Segmentation Model</h3><p>As we have experimented, we might have noticed that SAM’s predictions greatly rely on the presence of a prompt. As users, we need to define which part of the image the model should use to generate the mask. This approach introduces a new paradigm in segmentation tasks, where the user can exert control over the machine’s predictions. We can define the segmentation task to focus only on a specific area of the image. This is completely different from typical segmentation models, like U-Net or Mask R-CNN, where the mask is automatically generated without any user control.</p><p>However, with this flexibility in controlling SAM’s output, there comes a drawback: the need for additional effort in providing the prompt. This extra step requires a more interactive and hands-on approach, potentially increasing the time and complexity of the segmentation process. Users must accurately specify the regions of interest, which could be challenging in complex images, like our case does. Despite this, the ability to guide the model’s focus can lead to more precise and relevant segmentation outcomes, especially in cases where the area of interest is specific and well-defined.</p><h3>9. Conclusion</h3><p>In this project, we have explored the application of the Segment Anything Model (SAM) in medical image analysis, specifically for detecting anomalous tissues in brain MRI images. The model demonstrates commendable performance when the probable location of cancerous tissue is specified. However, its effectiveness diminishes when the location of the cancerous tissue is uncertain, underscoring the critical role of prompts in guiding SAM’s predictions.</p><p>Looking ahead, a potential direction for enhancing this approach could involve integrating SAM with variations of the YOLO (You Only Look Once) model. In this scenario, YOLO could first identify the location of cancerous tissues, followed by SAM’s detailed analysis of the size and extent of these tissues.</p><p>Since SAM is still in the early stages of development, particularly for natural image data, further research and improvements are essential to fully harness its capabilities in the realm of medical image analysis. This continuous advancement is key to unlocking more precise and reliable applications in medical diagnostics and treatment planning. Furthermore, SAM possesses the potential to create a new paradigm in medical image analysis. Its adaptability and performance in natural image data hint at a future where it could significantly advance the precision and effectiveness of medical diagnostics. This potential, coupled with ongoing research and enhancements, positions SAM as a promising tool in the evolution of medical image analysis, paving the way for innovative approaches in diagnosing and treating medical conditions.</p><p><strong>Project Code Reference:</strong></p><ul><li><a href="https://github.com/bowang-lab/MedSAM">bowang-lab/MedSAM: The official repository for MedSAM: Segment Anything in Medical Images. (github.com)</a></li><li><a href="https://docs.monai.io/en/latest/losses">https://docs.monai.io/en/latest/</a></li><li><a href="https://pytorch.org/">https://pytorch.org/</a></li><li><a href="https://github.com/bnsreenu/python_for_microscopists/blob/master/331_fine_tune_SAM_mito.ipynb">python_for_microscopists/331_fine_tune_SAM_mito.ipynb at master · bnsreenu/python_for_microscopists (github.com)</a></li><li><a href="https://github.com/rekalantar/MedSegmentAnything_SAM_LungCT">rekalantar/MedSegmentAnything_SAM_LungCT: The code to finetune SAM with bounding box prompt for segmentation of the lungs on CT (github.com)</a></li><li><a href="https://huggingface.co/docs/transformers/main/model_doc/sam">SAM (huggingface.co)</a></li><li><a href="https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Fine_tune_SAM_(segment_anything)_on_a_custom_dataset.ipynb">Transformers-Tutorials/SAM/Fine_tune_SAM_(segment_anything)_on_a_custom_dataset.ipynb at master · NielsRogge/Transformers-Tutorials (github.com)</a></li><li><a href="https://www.kaggle.com/code/matthewjansen/vision-brain-tumor-semantic-segmentation">Vision | Brain Tumor Semantic Segmentation | Kaggle</a></li></ul><p><strong>Article Writing Reference:</strong></p><ul><li><a href="https://arxiv.org/abs/2304.02643">[2304.02643] Segment Anything (arxiv.org)</a></li><li><a href="https://arxiv.org/abs/2305.03678">[2305.03678] Towards Segment Anything Model (SAM) for Medical Image Segmentation: A Survey (arxiv.org)</a></li><li><a href="https://www.v7labs.com/blog/foundation-models-guide">Foundation Models: The Benefits, Risks, and Applications (v7labs.com)</a></li><li><a href="https://encord.com/blog/learn-how-to-fine-tune-the-segment-anything-model-sam/">Learn how to fine-tune the Segment Anything Model (SAM) | Encord</a></li><li><a href="https://pyimagesearch.com/2023/09/11/sam-from-meta-ai-part-1-segmentation-with-prompts/?utm_source=Drip&amp;utm_medium=Email&amp;utm_campaign=WeeklyUpdate&amp;utm_content=11September2023NonUnivLink1DoYouHaveAnOpenCVProjectInMind">SAM from Meta AI (Part 1): Segmentation with Prompts — PyImageSearch</a></li><li><a href="https://learnopencv.com/segment-anything/">Segment Anything — A Foundation Model for Image Segmentation (learnopencv.com)</a></li><li><a href="https://segment-anything.com/">Segment Anything | Meta AI (segment-anything.com)</a></li><li><a href="https://towardsdatascience.com/segment-anything-promptable-segmentation-of-arbitrary-objects-f28958c5612d">Segment Anything: Promptable Segmentation of Arbitrary Objects | by Sascha Kirch | Towards Data Science</a></li><li><a href="https://medium.com/@rekalantar/segment-anything-model-sam-for-medical-image-segmentation-9344ba57f2ca">Segment Anything Model (SAM) for Medical Image Segmentation | by Reza Kalantar | Medium</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61393308f803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brain MRI Segmentation with Segment Anything Model (SAM) Part 1: Background — Data Preparation]]></title>
            <link>https://medium.com/@sdwiulfah/brain-mri-segmentation-with-segment-anything-model-sam-16d0b4101a85?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d0b4101a85</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 17:41:46 GMT</pubDate>
            <atom:updated>2024-01-03T16:37:08.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkJFImA9cE9rGSP1GTf1OQ.jpeg" /><figcaption>Brain MRI (source: <a href="https://alzheimersnewstoday.com/news/5-minute-brain-mri-can-reveal-risk-for-alzheimers-disease/">alzheimersnewstoday.com</a>)</figcaption></figure><blockquote>The implementation code can be found in Github or Kaggle.</blockquote><ul><li><a href="https://github.com/saskia-dwi-ulfah/sam_for_brain_MRI_segmentation">GitHub - saskia-dwi-ulfah/sam_for_brain_MRI_segmentation</a></li><li><a href="https://www.kaggle.com/code/saskiadwiulfah18/segment-anything-model-for-brain-mri-segmentation?kernelSessionId=155363687">Segment Anything Model for Brain MRI Segmentation</a></li></ul><h3>1. Problem Statement and Background</h3><p>Medical image segmentation is a crucial process in healthcare, specifically in the identification and delineation of anatomical structures within medical images. These structures include organs, lesions, and tissues, which are vital for accurate diagnosis and treatment planning. This technique is indispensable in clinical applications such as computer-aided diagnosis, treatment planning, and the monitoring of disease progression.</p><p>Brain MRI segmentation is particularly important in the detection and diagnosis of brain cancer. By accurately segmenting MRI images, clinicians can identify cancerous tissues, which is essential for determining the appropriate course of treatment. This process not only aids in early detection but also significantly improves the chances of successful treatment outcomes.</p><p>Existing brain MRI segmentation methods range from manual delineation by medical experts to more sophisticated automated techniques. Among the notable automated methods is the U-Net architecture, a convolutional neural network designed specifically for medical image analysis. Other methods include various algorithm-based approaches that strive to accurately identify and segment relevant brain structures, facilitating effective diagnosis and treatment planning.</p><p>The introduction of the Segment Anything Model (SAM) by META AI’s FAIR Lab in April 2023 represented a major advancement in image segmentation technology. Detailed in their groundbreaking paper “<a href="https://arxiv.org/abs/2304.02643">Segment Anything</a>”, SAM’s promptable-based architecture has brought a new level of versatility and accuracy to the field. Its ability to generate precise object masks automatically has set a new standard in the realm of image segmentation-related tasks. SAM, a model trained on the extensive SA-1B dataset, which includes 11 billion images and over 1 billion masks, primarily focuses on natural image data known for its pronounced edge details. This aspect markedly contrasts with typical medical imaging data, where the boundaries between objects are rarely as distinct.</p><p>This project aims to explore the effectiveness of SAM in the context of brain MRI imaging. Our objective is to utilize SAM’s advanced segmentation capabilities to create accurate and detailed masks for brain MRI scans. We anticipate that this exploration will significantly enhance the accuracy and efficiency of medical diagnoses and treatment planning, potentially ushering in a new era of technological advancement and clinical application in medical imaging.</p><h3>2. Segment Anything Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*QKhPnX7ozbwaMFflqnS9hA.png" /><figcaption>How SAM works (source: <a href="https://arxiv.org/pdf/2304.02643.pdf">Segment Anything paper</a>)</figcaption></figure><p>Segment Anything Model, a foundational (pretrained) model developed for image segmentation tasks, was launched by Meta AI in April 2023. Trained on an extensive dataset comprising 11 billion images and over 1 billion masks, known as the SA-1B dataset, SAM demonstrates remarkable zero-shot generalization abilities. A key feature of this model is its prompt-based interface, which allows users to input various types of prompts, such as points, bounding boxes, or text. The model then utilizes these prompts to generate precise segmentation masks on images, showcasing its adaptability and advanced understanding of image segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2IwgRG84OgTj_II4l_hZQ.gif" /><figcaption>SAM architecture (Source: <a href="https://towardsdatascience.com/segment-anything-promptable-segmentation-of-arbitrary-objects-f28958c5612d">towardsdatascience.com</a>)</figcaption></figure><p>The features of SAM are supported by 3 main components: image encoder, prompt encoder, and mask decoder.</p><h4>Image Encoder</h4><p><strong>The image encoder in SAM transforms the input image into</strong> a format that the model can understand. It takes an image and produces <strong>an image embedding (C x H x W)</strong>. Specifically, it uses the ViT-H/16 encoder, which reduces the image size by 16 times. For instance, an input image of 1024 x 1024 becomes a 64 x 64 output. To further simplify the image, the encoder employs a 1 x 1 convolution layer with 256 channels, followed by a 3 x 3 convolution layer also with 256 channels. Each convolution step includes a normalization layer to maintain image quality. The image encoder has 632M parameters.</p><h4><strong>Prompt Encoder</strong></h4><p>SAM, as a prompt-able model, uses prompts to generate masks. This part of SAM contains 4M parameters. SAM itself supports two types of prompts: sparse (points, boxes, and text) and dense (masks).<strong> The prompt encoder then converts these prompts into prompt embeddings</strong>:</p><ul><li>For sparse prompts, it transforms the prompt into a 256-dimensional embedding vector.</li><li>For dense prompts, the encoder downscales the prompt using two stride-2 convolutions and then applies a final 1×1 convolution to adjust the channel dimension to 256.</li></ul><h4><strong>Mask Decoder</strong></h4><p>The mask decoder is a crucial component that integrates the representations of both the image and the prompts to accurately <strong>predict the appropriate mask for the image</strong>.</p><h3>3. Dataset</h3><p>In this project, the <a href="https://www.kaggle.com/datasets/mateuszbuda/lgg-mri-segmentation/data">LGG segmentation dataset</a> is utilized. It comprises brain MRI scans paired with manually created segmentation masks highlighting FLAIR abnormalities. These images are sourced from The Cancer Imaging Archive (TCIA). They represent a subset of 110 patients from The Cancer Genome Atlas (TCGA) that focuses on lower-grade glioma, each having available data on fluid-attenuated inversion recovery (FLAIR) sequences and genomic clusters.</p><h3><strong>4. Library and Configuration</strong></h3><p>Moving forward, we will develop Python code to investigate the features of SAM. The first step in this process is to import the essential libraries. If executing this code leads to an error, ensure that all necessary packages are installed by using the pip install command.</p><pre># for general purposes<br>import random<br>import time<br>import warnings<br><br># for mathematical computation<br>import numpy as np<br>from statistics import mean<br><br># for visualization<br>import matplotlib.pyplot as plt<br>import matplotlib.patches as patches<br>import seaborn as sns<br>from tqdm.notebook import tqdm<br>from IPython.display import clear_output<br><br># for data management and manipulation<br>import os<br>import glob<br>import io<br>import cv2<br>import pandas as pd<br>import datasets as dts<br>from PIL import Image<br>from torch.utils.data import DataLoader<br>from torchvision import transforms<br>from monai.transforms import Compose, NormalizeIntensityd<br><br><br># for modeling and model evaluation<br>import torch<br>import monai<br>import torchvision<br>from sklearn.model_selection import train_test_split<br>from transformers import SamProcessor<br>from transformers import SamModel<br>from torch import nn<br>from torch.optim import Adam<br>from monai.metrics import compute_iou</pre><p>We will define a CFG class to encapsulate key variables that are essential throughout the execution of the code.</p><pre>class CFG:<br>    # define paths<br>    DATASET_PATH = &quot;/kaggle/input/lgg-mri-segmentation/&quot;<br>    TRAIN_PATH = &quot;/kaggle/input/lgg-mri-segmentation/kaggle_3m/&quot;<br>    <br>    DEVICE = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot; # if GPU available, use it to catalize the training process.<br>    TRAIN_BATCH_SIZE = 2 # the number of data to pass in each iteration throughout the network in training phase.<br>    TEST_BATCH_SIZE = 1 # the number of data to pass in each iteration throughout the network in testing phase.<br>    LEARNING_RATE = 1e-3 # how fast model will learn<br>    WEIGHT_DECAY = 0 # for regularization<br>    EPOCH = 10 # 1 epoch = all data have passed through network.</pre><h3>5. Data Preparation and Exploration</h3><p>Before inputting data into the model, it is essential to undergo several preprocessing steps. As observed on <a href="https://www.kaggle.com/datasets/mateuszbuda/lgg-mri-segmentation/data">this Kaggle site</a>, the data is organized into numerous folders. Within each folder, there are images along with their corresponding masks. The initial step involves retrieving the file paths for all these items.</p><pre># fetch the paths of all files<br>dataset_images = glob.glob(f&quot;{CFG.TRAIN_PATH}**/*.tif&quot;)</pre><h4>Constructing The Dataframe</h4><p>Subsequently, we will create a dataframe to organize the data details, including the file paths. This will also involve assigning an identifier to distinguish whether each file is an image or a mask. We will accomplish this using the following functions.</p><pre># get the patient details<br>def get_sample_patient_id(image_paths):<br>    return [(_.split(&#39;/&#39;)[-2:][0]) for _ in image_paths]<br><br># get the sample number<br>def get_sample_number(image_paths):<br>    sample_numbers = []<br>    is_mask = []<br><br>    for path in image_paths:<br>        path_list = path.split(&#39;/&#39;)[-2:][1].split(&#39;_&#39;)<br><br>        if &#39;mask.tif&#39; in path_list:<br>            sample_numbers.append(int(path_list[-2]))<br>            is_mask.append(1)<br>        else:<br>            sample_numbers.append(int(path_list[-1].replace(&#39;.tif&#39;, &#39;&#39;)))<br>            is_mask.append(0)<br><br>    return sample_numbers, is_mask<br><br># construct the dataframe<br>def build_df(image_paths):<br>    sample_numbers, mask_label = get_sample_number(image_paths)<br>    df = pd.DataFrame({<br>        &#39;id&#39;        : sample_numbers,<br>        &#39;patient&#39;   : get_sample_patient_id(image_paths),<br>        &#39;image_path&#39;: image_paths,<br>        &#39;is_mask&#39;   : mask_label<br>    })<br><br>    return df</pre><p>Here is what the dataframe appears like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1O6KXScRFJetPP-K396EQ.png" /><figcaption>Dataframe for the data details</figcaption></figure><p>Next, we will perform a groupby operation to segregate the dataframes, creating separate ones for images and masks. Following this, we will merge them so that the paths for both images and masks are aligned side-by-side.</p><pre># images_df: for images<br># mask_df: for masks<br><br>grouped_df = dataset_df.groupby(by=&#39;is_mask&#39;)<br>images_df, mask_df = (<br>    grouped_df.get_group(0).drop(&#39;is_mask&#39;, axis=1).reset_index(drop=True),<br>    grouped_df.get_group(1).drop(&#39;is_mask&#39;, axis=1).reset_index(drop=True)<br>)<br><br>mask_df = mask_df.rename({&#39;image_path&#39;: &#39;mask_path&#39;}, axis=1)<br><br>mask_df.head()</pre><pre># merge images dataframe and masks dataframe<br>ds = images_df.merge(<br>    mask_df,<br>    on=[&#39;id&#39;, &#39;patient&#39;],<br>    how=&#39;left&#39;<br>)</pre><p>Following this, we will generate labels for each data row by examining for abnormalities, indicated by the presence of pixels with a value of 1 in the mask. If such pixels are found, the diagnosis is labeled as 1, signifying cancerous tissue; if not, it is labeled as 0.</p><pre>def _load(image_path, as_tensor=True):<br>    image = Image.open(image_path)<br>    return np.array(image).astype(np.float32) / 255.<br><br>def generate_label(mask_path, load_fn):<br>    mask = load_fn(mask_path)<br>    if mask.max() &gt; 0:<br>        return 1 # brain tumor presents<br>    return 0 # normal</pre><pre># generate MRI Label<br>ds[&#39;diagnosis&#39;] = [generate_label(_, _load) for _ in tqdm(ds[&#39;mask_path&#39;])]<br>ds.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwGvNCgA7UZo2c692cAS7Q.png" /><figcaption>ds dataframe</figcaption></figure><p>For this project, our focus will be solely on the diagnosis of cancerous tissue. Therefore, we will limit our dataset to cases where the diagnosis equals 1, using a total of 1360 rows of data. This decision is guided by the need for simplicity and the constraints of our computational resources.</p><pre># filter valid masks and choose only 1360<br>ds = ds[ds[&#39;diagnosis&#39;]==1]<br>ds = ds.head(1360)</pre><h4>Train-Test Splitting</h4><p>A common practice in machine learning involves dividing our data into training and testing sets. We train our model using the training set and evaluate its performance with the testing set. To achieve this, we utilize the train_test_split()function from scikit-learn, which returns four components: training features, testing features, training labels, and testing labels. In our context, the “features” refer to the images, while the “labels” denote the masks.</p><pre># train-test splitting<br>image_train, image_test, mask_train, mask_test = train_test_split(<br>ds[&#39;image_path&#39;], ds[&#39;mask_path&#39;], test_size = 0.10)</pre><p>Next, we will merge the paths of the images and their corresponding masks into a single dataframe.</p><pre># train_df: contains the path to image and mask of training set<br>train_df = pd.concat([image_train, mask_train], axis=1).reset_index(drop=True)<br><br># test_df: contains the path to image and mask of testing set<br>test_df = pd.concat([image_test, mask_test], axis=1).reset_index(drop=True)</pre><p>For both the train_df and test_df, we will utilize the Dataset.from_pandas function from the datasetpackage, which we have aliased as dts. This function will encapsulate our data, facilitating ease in the modeling process.</p><pre>train_dataset = dts.Dataset.from_pandas(train_df)<br>test_dataset = dts.Dataset.from_pandas(test_df)</pre><p>For both train_dataset and test_dataset, we will apply transformations to ensure that each dataset stores both the image and its corresponding mask. The images will be stored in RGB format, while the masks will be stored as grayscale.</p><pre>def transform(data):<br>    # Load the image<br>    with open(data[&#39;image_path&#39;], &#39;rb&#39;) as f:<br>        image = Image.open(io.BytesIO(f.read())).convert(&#39;RGB&#39;)<br>    data[&#39;image&#39;] = image<br><br>    with open(data[&#39;mask_path&#39;], &#39;rb&#39;) as f:<br>        mask = Image.open(io.BytesIO(f.read())).convert(&#39;L&#39;) # to grayscale<br>    data[&#39;mask&#39;] = mask<br><br>    return data</pre><pre># input both image_path and mask_path to `transform()` and return the image and the mask<br><br>train_dataset = train_dataset.map(transform, remove_columns=[&#39;image_path&#39;,&#39;mask_path&#39;])<br>test_dataset = test_dataset.map(transform, remove_columns=[&#39;image_path&#39;,&#39;mask_path&#39;])</pre><p>Now, train_dataset and test_dataset store the files instead of the paths. For example:</p><pre># take random sample from train_dataset<br><br>example = train_dataset[0]<br>img = example[&#39;image&#39;]<br>msk = example[&#39;mask&#39;]</pre><p>If you call either img or msk , the respective image or mask will be rendered.</p><h4>Visualizing The Dataset</h4><p>Next, we will proceed with visualizing our data, a crucial step for a deeper understanding. By overlapping the image and the mask in one axes, we can effectively identify cancerous regions in the brain. This can be achieved using the following code snippet.</p><pre># code for showing the mask<br>def show_mask(mask, ax, random_color=False):<br>    if random_color:<br>        color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)<br>    else:<br>        color = np.array([30/255, 144/255, 255/255, 0.6])<br>    h, w = mask.shape[-2:]<br>    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)<br>    ax.imshow(mask_image)</pre><pre>fig, axes = plt.subplots()<br><br>axes.imshow(np.array(img))<br>ground_truth_seg = np.array(example[&quot;mask&quot;])<br>show_mask(ground_truth_seg, axes)<br>axes.title.set_text(f&quot;Ground truth mask&quot;)<br>axes.axis(&quot;off&quot;)</pre><p>The above code is resulting this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*wvodoZBoAOFLOHdzaNL0_Q.png" /><figcaption>Plot of the image and its mask</figcaption></figure><h4>Defining The Dataset Class</h4><p>To prepare our data for input into our model, several processing steps are necessary to align with the model’s requirements. Our system, SAM, is built using the PyTorch framework, which facilitates dataset processing through the use of Dataset and DataLoader classes. The following code snippets illustrate how these are implemented in our context.</p><pre>class SAMDataset(torch.utils.data.Dataset):<br>  def __init__(self, dataset, processor):<br>    self.dataset = dataset<br>    self.processor = processor<br>   <br>  def __len__(self):<br>    return len(self.dataset)<br><br>  def __getitem__(self, idx):<br>    item = self.dataset[idx]<br>    image = item[&quot;image&quot;]<br>    ground_truth_mask = np.array(item[&quot;mask&quot;])<br><br>    # get bounding box prompt<br>    prompt = get_bounding_box(ground_truth_mask)<br><br>    # prepare image and prompt for the model<br>    inputs = self.processor(image, input_boxes=[[prompt]], return_tensors=&quot;pt&quot;)<br><br>    # remove batch dimension which the processor adds by default<br>    inputs = {k:v.squeeze(0) for k,v in inputs.items()}<br><br>    # add ground truth segmentation<br>    inputs[&quot;ground_truth_mask&quot;] = ground_truth_mask/255<br><br>    return inputs</pre><pre>def get_bounding_box(ground_truth_map):<br>    &#39;&#39;&#39;<br>    This function creates varying bounding box coordinates based on the segmentation contours as prompt for the SAM model<br>    The padding is random int values between 5 and 20 pixels<br>    &#39;&#39;&#39;<br><br>    if len(np.unique(ground_truth_map)) &gt; 1:<br><br>        # get bounding box from mask<br>        y_indices, x_indices = np.where(ground_truth_map &gt; 0)<br>        x_min, x_max = np.min(x_indices), np.max(x_indices)<br>        y_min, y_max = np.min(y_indices), np.max(y_indices)<br><br>        # add perturbation to bounding box coordinates<br>        H, W = ground_truth_map.shape<br>        x_min = max(0, x_min - np.random.randint(5, 20))<br>        x_max = min(W, x_max + np.random.randint(5, 20))<br>        y_min = max(0, y_min - np.random.randint(5, 20))<br>        y_max = min(H, y_max + np.random.randint(5, 20))<br><br>        bbox = [x_min, y_min, x_max, y_max]<br><br>        return bbox<br>    else:<br>        return [0, 0, 256, 256]</pre><pre>processor = SamProcessor.from_pretrained(&quot;facebook/sam-vit-base&quot;, do_normalize=False)</pre><pre>train_sam_ds = SAMDataset(dataset=train_dataset, processor=processor)</pre><p>First, we will define SAMDataset for our custom dataset, a class that inherits from torch.utils.data.Dataset. When creating a class for a custom dataset in PyTorch, it is essential to include three mandatory methods: __init__(), __len__(), and __get_item()__.</p><ul><li>The __init__() function in the SAMDataset class is automatically executed upon instantiation of the class. Within this function, 2 variables are assigned: self.dataset, which holds the set of image-mask pairs, and self.processor, which refers to the SAM processor. The SAM processor is designed to transform the data, ensuring it is appropriately formatted for the SAM model.</li><li>The __len__() function is designed to return the number of image-mask pairs in the dataset. Essentially, it indicates the total amount of data available in the dataset.</li><li>The __getitem__() function is called when accessing data from the dataset. It begins by retrieving the data at the specified index, namely the image and its corresponding mask. The mask is converted into an array, a necessary step for extracting the bounding box location. Given that SAM is a prompt-able segmentation model, it requires a prompt to identify a valid mask for each image. In this project, the bounding box serves as this prompt. To determine the bounding box, we employ the get_bounding_box() function, which identifies the location of cancerous tissue in the ground truth mask. This function searches for pixels with a value of 1 and creates a bounding box encompassing these areas. Both the MRI image and the generated prompt are then processed through self.processor() (the SAM processor). This processor outputs several values. Subsequently, we remove the batch dimension added by default during processing. Finally, we scale each pixel value of the ground truth mask by dividing by 255. This normalization ensures that pixel values range between 0 and 1, a crucial step for evaluating model performance later in the modeling phase and for preventing anomalous values during training.</li></ul><p>After defining the SAMDataset class, we proceed to utilize it. The first step is to define the processor using SamProcessor.from_pretrained(), specifying the variant of the processor to be used. In this instance, we opt for the variant released by Facebook: facebook/sam-vit-base. For exploring other variants, refer to the provided <a href="https://huggingface.co/models?other=sam">link</a>.</p><p>SamProcessor.from_pretrained() has parameter do_normalize. This parameter is used if we want to normalize the pixel values by specific mean or standard deviation. This process of normalization may risk in resulting negative pixel values. By setting the parameter do_normalize to False, we explicitly indicate that we do not wish to normalize the pixel values in the MRI images. This process ensure no negative values are being fed to the network.</p><p>By default, the processor performs rescaling (do_rescale = True), ensuring that each pixel value in the MRI images is within the range of 0 to 1. Scaling is nothing but multiplying the pixel values with a constant. In this case, 1/255. This rescaling is vital as it guarantees that the model processes values between 0 and 1 for both the image and the mask, maintaining consistency in data handling and model performance.</p><p>Finally, we utilize all of the class functionality and pass train_dataset and processor.</p><h4>Defining The DataLoader</h4><p>During model training, data is not loaded all at once but in mini-batches. Each iteration involves passing a mini-batch of data through the model. Completing one pass of all the data constitutes an epoch, meaning an epoch comprises several iterations.</p><p>To manage the loading of these mini-batches, we employ the DataLoader class. This class accepts a batch_size argument, which defines the quantity of data to be passed to the network in each iteration. For our purposes, we will set batch_size = 2. This configuration allows for efficient data processing, balancing computational load and training speed.</p><pre># DataLoader to enable iteration during training process<br># batch_size = 2<br><br>train_dataloader = DataLoader(train_sam_ds, batch_size=CFG.TRAIN_BATCH_SIZE, shuffle=False)</pre><blockquote><a href="https://medium.com/@sdwiulfah/brain-mri-segmentation-with-segment-anything-model-sam-part-2-modeling-conclusion-61393308f803">Click here</a> to the part 2 of this article.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d0b4101a85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Having Fun with YOLOv8: How Good Your Model in Detecting Playing Card?]]></title>
            <link>https://medium.com/@sdwiulfah/having-fun-with-yolov8-how-good-your-model-in-detecting-playing-card-a468a02e4775?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/a468a02e4775</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 19:23:57 GMT</pubDate>
            <atom:updated>2024-01-20T08:47:39.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MRhSR-6PawdvZlYp.JPG" /><figcaption>Playing Card (source: <a href="https://en.wikipedia.org/wiki/Playing_card">en.wikipedia.org</a>)</figcaption></figure><p><em>It’s been a while since my post in a casual language style. In the midst of my office’s probation period, there was some urge to express something inside me (I don’t even know what I am saying, lol! </em>🤪<em>) through writing some paragraphs. So, here I am, take my time to train YOLOv8 on </em><a href="https://www.kaggle.com/datasets/andy8744/playing-cards-object-detection-dataset/data"><em>playing card dataset</em></a><em> and make this article for you. Sit back, relax an!</em></p><p>Full code of this project can be found <a href="https://github.com/saskia-dwi-ulfah/playing-card-detection-yolov8">here</a>!</p><h3>Introduction</h3><p>Who doesn’t like playing a card? I bet some of you still play cards even though online games are nowadays more popular. If you say that you have never played a card before, for the sake of God, I believe once in a lifetime at least you have seen playing cards😶.</p><p>Okay, now it’s time for a little bit of theory.</p><p>Playing cards are a set of cards illustrated with either 4 motives: clubs (♣), diamonds (♦), hearts (♥) or spades (♠). Each motive will be numbered with A, 2–9, K, Q, J. Hence, each motive will have 13 variations in the way it is numbered. In total, a set of playing cards consists of 52 cards.</p><p>By a natural human vision, we can easily identify which number and motive in a card. However, how can we adopt this intuition of our vision and internalize it to a machine, so it can see, the way our eyes see?</p><blockquote>This typical of problem can be seen as <a href="https://blog.roboflow.com/object-detection/"><strong>object detection</strong></a> problem!</blockquote><h3>Object Detection Nitty-Gritty</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*Aq91peWvsmS6r-4q.jpg" /><figcaption>Intuition of Object Detection (source: <a href="https://blog.jetbrains.com/kotlin/2022/01/object-detection-with-kotlindl-and-ktor/">blog.jetbrains.com</a>)</figcaption></figure><h4><strong>Introduction to Object Detection</strong></h4><p>As it is named, think of object detection as a way for our computer <strong>to locate and identify/classify </strong>what’s presence inside its focus of vision (marked by bounding box around objects).</p><p>With the advancement in the field of artificial intelligence for vision, researchers (or at least what Google told me) identify two groups of object detection techniques.</p><h4><strong>Two-State Detector and One-Stage Detector</strong></h4><ol><li><strong>Two-Stage Detector</strong></li></ol><p>Notice that object detection is made up of two tasks: localization (to locate the position of object) and classification (to identify the class of object). In one stage detector techniques, the algorithm does those tasks separately.</p><ul><li>In the first stage, the model generates a set of region proposals that might contain objects.</li><li>In the second stage, the model classifies these regions into object categories and refines the bounding boxes.</li></ul><p>Lists of state-of-the-art two-stage detector algorithms include R-CNN, Fast R-CNN and Faster R-CNN.</p><p>2. <strong>One-Stage Detector</strong></p><p>Contrarily to two stage detector, one stage detector does localization and classification in one step. The model directly predicts the class and bounding box coordinates for objects in an image in one go.</p><p>Lists of state-of-the-art one-stage detector algorithms include SSD (Single Shot Detector) and YOLO (You Only Look Once).</p><h4>YOLOv8</h4><p>YOLOv8 is the newest version of the YOLO model series, created by a company called Ultralytics. It’s designed to do several things like recognizing objects in pictures, dividing images into different sections, and classifying what’s in the images. This version of YOLO makes some big improvements over the older ones.</p><p>One of the main changes in YOLOv8 is that it doesn’t use anchor boxes anymore. Anchor boxes were a way to guess where objects might be in an image, but they could make things more complicated. Now, YOLOv8 directly figures out where the center of an object is, which makes it simpler and often works better.</p><p>The model has also been updated in how it processes images. These changes help it to better identify and classify objects. YOLOv8 uses a special technique called mosaic augmentation during training. This involves putting together different images to make new ones, which helps the model learn to recognize objects in various situations. But, this technique is not used in the last part of training to make sure the model works well.</p><p>YOLOv8 is good because it’s fast and accurate, which is important for detecting objects in real-time, like in video feeds. It’s versatile and can be used for different tasks, from simple object recognition to more complex ones like segmenting images or figuring out human poses. You can use YOLOv8 through Python programming or with command-line tools, which makes it useful for many people.</p><p>In tests, like the COCO dataset challenge, YOLOv8 has shown that it’s really good at what it does, better than the older YOLO models. It’s faster and more accurate, which makes it a top choice for these kinds of tasks.</p><h4>YOLOv8 for Playing Card Detection</h4><p>Now, we have a handful of important basics about object detection and YOLOv8 which we will use in our project. In this part, we will experiment with YOLOv8’s functionality for detecting playing cards. The data source is from <a href="https://www.kaggle.com/datasets/andy8744/playing-cards-object-detection-dataset">this Kaggle site</a>.</p><p>When working with the YOLO model, we expect our data to be organized as shown in the image below. Each set should have an images folder and a corresponding labels folder. The number of files in the images and labels folders is expected to be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*m53JzczaMJwUXToLvuFzJg.png" /><figcaption>YOLO project folder structure</figcaption></figure><ul><li>In the images folder, we store plain images.</li><li>In the labels folder, we store annotations for each image. Annotations are usually saved as a .txt file and contain a set of numbers to locate the bounding box position in the image.</li></ul><p>Having our project folder structure ready, we need to prepare a .YAML file. This file holds the detail for training purpose. In this file, we define the location of training folder, the number of classes to be predicted, .etc. This is how our .YAML file looks like. Since we want to detect playing cards, we have 52 classes to be predicted.</p><pre>train: /kaggle/working/playing-cards-object-detection-dataset/train/images<br>val: /kaggle/working/playing-cards-object-detection-dataset/valid/images<br>test: /kaggle/working/playing-cards-object-detection-dataset/test/images<br><br>nc: 52<br>names: [&#39;10c&#39;, &#39;10d&#39;, &#39;10h&#39;, &#39;10s&#39;, <br>        &#39;2c&#39;, &#39;2d&#39;, &#39;2h&#39;, &#39;2s&#39;, <br>        &#39;3c&#39;, &#39;3d&#39;, &#39;3h&#39;, &#39;3s&#39;, <br>        &#39;4c&#39;, &#39;4d&#39;, &#39;4h&#39;, &#39;4s&#39;, <br>        &#39;5c&#39;, &#39;5d&#39;, &#39;5h&#39;, &#39;5s&#39;, <br>        &#39;6c&#39;, &#39;6d&#39;, &#39;6h&#39;, &#39;6s&#39;, <br>        &#39;7c&#39;, &#39;7d&#39;, &#39;7h&#39;, &#39;7s&#39;, <br>        &#39;8c&#39;, &#39;8d&#39;, &#39;8h&#39;, &#39;8s&#39;, <br>        &#39;9c&#39;, &#39;9d&#39;, &#39;9h&#39;, &#39;9s&#39;, <br>        &#39;Ac&#39;, &#39;Ad&#39;, &#39;Ah&#39;, &#39;As&#39;, <br>        &#39;Jc&#39;, &#39;Jd&#39;, &#39;Jh&#39;, &#39;Js&#39;, <br>        &#39;Kc&#39;, &#39;Kd&#39;, &#39;Kh&#39;, &#39;Ks&#39;, <br>        &#39;Qc&#39;, &#39;Qd&#39;, &#39;Qh&#39;, &#39;Qs&#39;]<br></pre><p>Prior to the modeling phase, we usually want to ensure that our data is annotated correctly and that each annotation coordinate accurately locates the exact position of the card class. We will make a function to sample a number of images to be visualized.</p><pre>def visualize_image_with_annotation_bboxes(image_dir, label_dir):<br>    # Get list of all the image files in the directory<br>    image_files = sorted(os.listdir(image_dir))<br><br>    # Choose 12 random image files from the list<br>    sample_image_files = random.sample(image_files, 12)<br><br>    # Set up the plot<br>    fig, axs = plt.subplots(4, 3, figsize=(15, 20))<br><br>    # Loop over the random images and plot the bounding boxes<br>    for i, image_file in enumerate(sample_image_files):<br>        row = i // 3<br>        col = i % 3<br><br>        # Load the image<br>        image_path = os.path.join(image_dir, image_file)<br>        image = cv2.imread(image_path)<br>        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br><br>        # Load the labels for this image<br>        label_path = os.path.join(label_dir, image_file[:-4] + &#39;.txt&#39;)<br>        f = open(label_path, &#39;r&#39;)<br><br>        # Loop over the labels and plot the bounding boxes<br>        for label in f:<br>            class_id, x_center, y_center, width, height = map(float, label.split())<br>            h, w, _ = image.shape<br>            x_min = int((x_center - width/2) * w)<br>            y_min = int((y_center - height/2) * h)<br>            x_max = int((x_center + width/2) * w)<br>            y_max = int((y_center + height/2) * h)<br>            cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)<br>            cv2.putText(image, Idx2Label[int(class_id)], (x_min, y_min), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=(255, 255, 255), thickness=2)<br><br>        axs[row, col].imshow(image)<br>        axs[row, col].axis(&#39;off&#39;)<br><br>    plt.show()</pre><pre>visualize_image_with_annotation_bboxes(train_images, train_labels)</pre><p>When we run the code above, this is how the output looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*MSARyMgE7ksfFomnKr4nkw.png" /><figcaption>Visualize image and its annotation</figcaption></figure><p>Subsequently, we will attempt to train our Ultralytics YOLOv8 model. Ultralytics provides a YOLO() object where we can pass an argument defining the variant to be used. Here, we will use the yolov8n variant.</p><pre># Load a pretrained nano model<br>model = YOLO(&#39;yolov8n.pt&#39;)</pre><p>We have now reached an important stage: initiating the training process of our model. In this phase, we activate the model’s training mode. When working within a notebook environment, such as the one we are currently using, this is accomplished by employing the .train() method of our defined model. In executing this method, we input our data.yaml along with other necessary training parameters.</p><pre>results = model.train(<br>    data= yaml_path,<br>    epochs = 25,<br>    imgsz = (height, width, channels),<br>    seed = 42,<br>    batch = 8,<br>    workers = 4,<br>    patience = 5,<br>    name = &#39;yolov8n_custom&#39;)</pre><p>Upon initiating the training process, a ‘run’ folder will be generated. This folder is an essential component as it stores all the outcomes of our training, including the vital training metrics. Following the completion of the training, we will engage in a typical post-training activity: plotting these training metrics for each epoch.</p><pre># plot the result<br><br>%matplotlib inline<br># read in the results.csv file as a pandas dataframe<br>df = pd.read_csv(&#39;/kaggle/working/runs/detect/yolov8n_custom3/results.csv&#39;)<br>df.columns = df.columns.str.strip()<br><br># create subplots using seaborn<br>fig, axs = plt.subplots(nrows=5, ncols=2, figsize=(15, 15))<br><br># plot the columns using seaborn<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;train/box_loss&#39;, data=df, ax=axs[0,0])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;train/cls_loss&#39;, data=df, ax=axs[0,1])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;train/dfl_loss&#39;, data=df, ax=axs[1,0])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;metrics/precision(B)&#39;, data=df, ax=axs[1,1])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;metrics/recall(B)&#39;, data=df, ax=axs[2,0])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;metrics/mAP50(B)&#39;, data=df, ax=axs[2,1])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;metrics/mAP50-95(B)&#39;, data=df, ax=axs[3,0])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;val/box_loss&#39;, data=df, ax=axs[3,1])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;val/cls_loss&#39;, data=df, ax=axs[4,0])<br>sns.lineplot(x=&#39;epoch&#39;, y=&#39;val/dfl_loss&#39;, data=df, ax=axs[4,1])<br><br># set titles and axis labels for each subplot<br>axs[0,0].set(title=&#39;Train Box Loss&#39;)<br>axs[0,1].set(title=&#39;Train Class Loss&#39;)<br>axs[1,0].set(title=&#39;Train DFL Loss&#39;)<br>axs[1,1].set(title=&#39;Metrics Precision (B)&#39;)<br>axs[2,0].set(title=&#39;Metrics Recall (B)&#39;)<br>axs[2,1].set(title=&#39;Metrics mAP50 (B)&#39;)<br>axs[3,0].set(title=&#39;Metrics mAP50-95 (B)&#39;)<br>axs[3,1].set(title=&#39;Validation Box Loss&#39;)<br>axs[4,0].set(title=&#39;Validation Class Loss&#39;)<br>axs[4,1].set(title=&#39;Validation DFL Loss&#39;)<br><br># add suptitle and subheader<br>plt.suptitle(&#39;Training Metrics and Loss&#39;, fontsize=24)<br><br># adjust top margin to make space for suptitle<br>plt.subplots_adjust(top=0.8)<br><br># adjust spacing between subplots<br>plt.tight_layout()<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*C1ssMYm2y6RJUhMaDpDa7A.png" /><figcaption>Plot of metrics</figcaption></figure><p>After running 25 epochs of training, we observed that our model performs well in detecting our card symbols. Now, for the last part, we will try to test the model’s ability with completely new data.</p><pre># Function to perform detections with trained model<br>def predict_detection(image_path):<br>    # Read the image<br>    image = cv2.imread(image_path)<br><br>    # Pass the image through the detection model and get the result<br>    detect_result = model(image)<br><br>    # Plot the detections<br>    detect_image = detect_result[0].plot()<br><br>    # Convert the image to RGB format<br>    detect_image = cv2.cvtColor(detect_image, cv2.COLOR_BGR2RGB)<br><br>    return detect_image</pre><pre># Get list of all the image files in the test directory<br>image_files = sorted(os.listdir(test_images))<br><br># Choose 12 random image files from the list<br>sample_image_files = random.sample(image_files, 12)<br><br># Set up the plot<br>fig, axs = plt.subplots(4, 3, figsize=(15, 20))<br><br># Loop over the random images and plot the detections of the trained model<br>for i, image_file in enumerate(sample_image_files):<br>    row = i // 3<br>    col = i % 3<br><br>    # Load the current image and run object detection<br>    image_path = os.path.join(test_images, image_file)<br>    detect_image = predict_detection(image_path)<br><br>    axs[row, col].imshow(detect_image)<br>    axs[row, col].axis(&#39;off&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKVJwDgXnxaDF-TL-sJKVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtJzMWFmw1le4JvBtFPvjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmSwQgiVdMVn9UWt3kFyBQ.png" /><figcaption>Inference on new data</figcaption></figure><p><strong>Reference</strong></p><ul><li><a href="https://docs.ultralytics.com/">Home — Ultralytics YOLOv8 Docs</a></li><li><a href="https://www.kaggle.com/datasets/andy8744/playing-cards-object-detection-dataset">Playing Cards Object Detection Dataset (kaggle.com)</a></li><li><a href="https://encord.com/blog/yolo-object-detection-guide/">YOLO models for Object Detection Explained [YOLOv8 Updated] | Encord</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a468a02e4775" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eksplorasi Karakteristik Bunga Iris dengan Tableau]]></title>
            <link>https://medium.com/@sdwiulfah/eksplorasi-karakteristik-bunga-iris-dengan-tableau-784a0eb89198?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/784a0eb89198</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 14:50:27 GMT</pubDate>
            <atom:updated>2023-08-20T15:41:05.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbwUtljCQYoeSgfKWclcng.jpeg" /><figcaption>Bunga Iris (source: <a href="https://en.wikipedia.org/wiki/Iris_sanguinea">wikipedia</a>)</figcaption></figure><blockquote><em>Tulisan ini merupakan </em>easy report <em>untuk</em> project<em> Pacmann </em>course<em>: </em>Introduction to Visualization<em>.</em></blockquote><h3><em>DATASET</em></h3><p><a href="https://www.kaggle.com/datasets/saurabh00007/iriscsv">Iris Plant Database</a> merupakan <em>dataset </em>yang berisi data pengukuran bagian-bagian bunga iris yang terdiri dari 3 kelas: iris setosa, iris versicolor, dan iris virginica.<em> Dataset </em>ini berisikan 150 baris (setiap spesies iris terdiri atas 50 baris) dengan 4 kolom numerik (pengukuran dalam cm):</p><ul><li>Panjang petal (<em>petal length</em>).</li><li>Lebar petal (<em>petal width</em>).</li><li>Panjang sepal (<em>sepal length</em>).</li><li>Lebar sepal (<em>sepal width</em>).</li></ul><h3>OBJEKTIF EKSPLORASI</h3><p>Dengan fitur-fitur yang terdapat pada <em>dataset</em>, tujuan dari eksplorasi ini adalah m<strong>enentukan kecenderungan karakteristik setiap spesies iris.</strong></p><h3><strong>VISUALISASI DENGAN TABLEAU</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZCUfd-KvfugSIegk_uQgQ.png" /><figcaption>Dashboard Tableau untuk Data Iris</figcaption></figure><p>Untuk mencapai objektif, digunakan <em>tools </em>Tableau untuk melakukan visualisasi dalam bentuk <em>dashboard</em>. Secara umum, <em>dashboard </em>ini memiliki 3 visualisasi:</p><ul><li><em>Pie chart </em>yang menunjukkan proporsi banyak data untuk setiap spesies iris.</li><li><em>Scatterplot </em>yang menunjukkan hubungan panjang petal (<em>petal length</em>) dan lebar petal (<em>petal width</em>).</li><li><em>Scatterplot </em>yang menunjukkan hubungan panjang sepal (<em>sepal length</em>) dan lebar sepal (<em>sepal width</em>).</li></ul><p>Selain itu, <em>dashboard </em>ini juga dilengkapi dengan filter yang memudahkan pengguna untuk memahami karakteristik setiap spesies secara individu.</p><h3><strong>INSIGHT</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZCUfd-KvfugSIegk_uQgQ.png" /><figcaption>Dashboard Tableau untuk Data Iris</figcaption></figure><p>Berdasarkan gambar di atas, terlihat bahwa <em>s</em><strong><em>catterplot </em>antara <em>petal length </em>dan <em>petal width</em> menunjukkan pola yang mudah dipahami untuk membedakan ketiga spesies iris</strong> dibandingkan <em>scatterplot </em>antara <em>sepal length </em>dan <em>sepal width</em>.</p><p>Pada <em>scatterplot </em>antara<em> petal length</em> dan <em>petal width, </em>terdapat kecenderungan bahwa <strong>semakin besar nilai <em>petal length, </em>maka semakin besar juga nilai<em> petal width</em></strong><em>. </em>Selain itu,<em> scatterplot </em>tersebut menunjukkan perbedaan karakteristik fisik antara ketiga spesies iris<em>. </em>Hal ini terlihat dari 3 <em>cluster</em> yang terbentuk.<strong> Iris setosa merupakan spesies iris dengan fitur fisik yang paling kecil</strong> dibandingkan dengan iris versicolor dan iris virginica. Sementara itu, <strong>iris virginica memiliki nilai <em>petal length </em>dan <em>petal width</em> yang paling besar</strong> di antara kedua spesies iris lainnya. <strong>Iris versicolor memiliki karakteristik fisik pertengahan</strong> antara iris setosa dan iris virginica.</p><p>Adapun <em>range </em>nilai <em>petal length </em>dan <em>petal width </em>untuk setiap spesies dapat diamati lebih jelas dengan melakukan <em>filtering.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q-XLZ3eYwQrEYiD8zZdVg.png" /><figcaption>Filtering Iris Setosa</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dm4zBMGIA8RldLMurHtGjA.png" /><figcaption>Filtering Iris Versicolor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcA7v6swUB8EteSV9O086g.png" /><figcaption>Filtering Iris Virginica</figcaption></figure><ul><li><em>Range </em>panjang petal untuk iris setosa: 1–1,9 cm. <em>Range lebar </em>petal untuk iris setosa: 0,1–0,6 cm.</li><li><em>Range </em>panjang petal untuk iris versicolor: 3–5,1 cm. <em>Range lebar </em>petal untuk iris versicolor: 1–1,8 cm.</li><li><em>Range </em>panjang petal untuk iris virginica: 4,5–6,9 cm. <em>Range lebar </em>petal untuk iris virginica: 1,4–2,5 cm.</li></ul><h3>AKSES DASHBOARD DAN DATA</h3><p><em>File dashboard </em>dan data yang digunakan dapat diunduh <a href="https://drive.google.com/drive/folders/1e3gGcWGq3gnYm02KmW2BxSkh6ZWNfXGx?usp=sharing">di sini</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=784a0eb89198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Astroworld Tragedy: What Do Twitter Users Say?]]></title>
            <link>https://medium.com/@sdwiulfah/astroworld-tragedy-what-do-twitter-users-say-ee7ee18960a4?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7ee18960a4</guid>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 11:09:03 GMT</pubDate>
            <atom:updated>2022-12-15T18:07:06.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJTQHDS4WZLPBqRPCNWpGw.jpeg" /><figcaption>Source: <a href="http://www.cnbc.com/">www.cnbc.com</a></figcaption></figure><p><em>This post is further explanation of my sentiment analysis final project in Natural Language Processing class. Full code can be found </em><a href="https://github.com/saskia-dwi-ulfah/travis-scott-astroworld-sentiment-analysis"><em>here</em></a><em>.</em></p><h3><strong>Problem Background and Objective</strong></h3><p>On early November 2021, the whole world’s attention was dragged to Astroworld Tragedy. According to <a href="http://www.cnbc.com/">www.cnbc.com</a>, at least 8 people were reported dead, and others were injured during the performing concert of Travis Scott.</p><p>“The crowd began to compress towards the front of the stage, and that caused some panic, and it started causing some injuries. People began to fall out, become unconscious, and it created additional panic.” Houston Fire Chief Samuel Peña reported to the reporters regarding the cause of this chaotic situation.</p><p>Travis Scott has received a lot of criticism for continuing to carry on with his concert in the middle of this chaotic situation. On November 7th, 2021, it was observed more than 400k+ people tweeted as a reaction towards this tragedy. It was also observed from Google Trends that ‘Travis Scott’ keyword reached its peak from November 7th 2021 and the following days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*8RkVVBTHeUWRzTW-KH220A.png" /><figcaption>Google Trends result for “Travis Scott” keyword</figcaption></figure><p>Based on this massive amount of reaction, the opinion mining or sentiment analysis was done to analyze what kind of emotion resides in dozens of tweets regarding this tragedy.</p><h3><strong>Project Breakdown</strong></h3><h4><strong>Google Colaboratory: An Interactive Working Environment</strong></h4><p>To work on my code, I would prefer using Google Colaboratory rather than using similar tools. Google Colaboratory is equipped with our needed dependencies, so it won’t take a lot of resources. In addition, it facilitates team collaboration and integrates with Google Drive.</p><h4><strong>Library</strong></h4><p>First, we need to import the necessary libraries</p><pre># General libraries<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Library for acquiring data<br>import tweepy as tw<br><br># Library for text preprocessing<br>import re<br>import string<br>import nltk<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import WordNetLemmatizer<br><br># Library for manual labeling<br>from textblob import TextBlob<br>from nltk.sentiment.vader import SentimentIntensityAnalyzer<br><br># Library for training preparation<br>from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># Library for ML algorithm<br>from sklearn.naive_bayes import GaussianNB, MultinomialNB<br>from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier<br>from lightgbm import LGBMClassifier<br>from xgboost import XGBClassifier<br>from catboost import CatBoostClassifier<br><br># Library for model performance<br>from sklearn.metrics import make_scorer, confusion_matrix, classification_report, precision_score, recall_score, f1_score<br><br># Library for generating wordcloud<br>from PIL import Image<br>from wordcloud import WordCloud, STOPWORDS</pre><ul><li>On the first block of code, we import numpy as an array-based computation library, pandas as a common library for data handling, matplotlib.pyplot and seaborn for visualization purposes.</li><li>On the second block of code, we import Tweepy. This library acts an API to acquire data from Twitter.</li><li>On the third block of code, we import all libraries for text processing purposes.</li><li>On the fourth block of code, we import all tools for manual data labeling. Those tools provide functionality to determine sentiment of the text automatically. Since our purpose is to train predictive model, we will employ those tools for preparing training data.</li><li>On the fifth block of code, we import all tools for training preparation.</li><li>On the sixth block of code, we import all models we want to compare.</li><li>On the seventh block of code, we import all necessities to evaluate model performance.</li><li>On the last block of code, we import all tools for generating a word cloud.</li></ul><h4><strong>Before going to next part…</strong></h4><p>Run the following codes to ensure there will be no errors in the next sections.</p><pre>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;vader_lexicon&#39;)<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><ul><li>On the first up to the third line, we download all the dependencies needed to run sentiment analysis.</li><li>The fourth line aims to ignore all warning that potentially occurs when we run the code.</li></ul><pre>np.set_printoptions(threshold=sys.maxsize)<br>pd.set_option(&#39;display.max_colwidth&#39;, -1)<br>pd. set_option(&#39;display.max_rows&#39;, 600) <br>sns.color_palette(&#39;Spectral&#39;)<br>sns.set_style(&#39;whitegrid&#39;)</pre><ul><li>Basically, the above codes are the default styles for the output of numpy, pandas, and seaborn libraries.</li></ul><pre>stop_words = set(stopwords.words(&#39;english&#39;))</pre><ul><li>Here, we take all kinds of stop words in the English language.</li></ul><p>Now, we are good to go.</p><h4><strong>Acquire the data</strong></h4><p>Below are the functions we will employ to get data from Twitter.</p><pre>def twitter_access(twitter_account):<br><br>  consumer_api_key = twitter_account.loc[0,&#39;Id&#39;]<br>  consumer_api_key_secret = twitter_account.loc[1,&#39;Id&#39;]<br>  access_token = twitter_account.loc[2,&#39;Id&#39;]<br>  access_token_secret = twitter_account.loc[3,&#39;Id&#39;]<br><br>  return consumer_api_key, consumer_api_key_secret, access_token, access_token_secret</pre><ul><li>This function is an interface to get all keys and tokens needed to interact with Twitter API. I save my keys and tokens in a CSV file.</li></ul><pre>def twitter_api(consumer_api_key, consumer_api_key_secret, access_token, access_token_secret):<br><br>  authenticate = tw.OAuthHandler(consumer_api_key, consumer_api_key_secret)<br>  authenticate.set_access_token(access_token, access_token_secret)<br>  api = tw.API(authenticate)<br><br>  return api</pre><ul><li>Next, we will use the output from the previous function as input for the above function. This function will return an API object. We will use this API for fetching tweets with a specific keyword.</li></ul><pre>def tweets_fetching(api, keyword, num_of_tweets, since_date=None, until_date=None):<br><br>  raw_tweets_list = []<br><br>  tweets = tw.Cursor(api.search, <br>                     q=keyword+&#39;-filter:retweets&#39;, <br>                     lang=&#39;en&#39;,<br>                     since=since_date,<br>                     until=until_date, <br>                     tweet_mode=&#39;extended&#39;).items(num_of_tweets)<br><br>  for tweet in tweets:<br>    raw_tweets_list.append(tweet.full_text)<br>  <br>  return raw_tweets_list  </pre><ul><li>This is the main part where we will take the data. Here, we pass the API object, the keyword for the tweets, and the number of tweets we want to get.</li><li>This function returns all the tweets in the form of list.</li></ul><p>Next, we call all of our defined functions.</p><pre>twitter_account = pd.read_csv(&#39;Twitter Developer Account.csv&#39;)<br>consumer_api_key, consumer_api_key_secret, access_token, access_token_secret = twitter_access(twitter_account)<br>api = twitter_api(consumer_api_key, consumer_api_key_secret, access_token, access_token_secret)<br>raw_tweets_list = tweets_fetching(api, &#39;Astroworld AND Travis Scott&#39;, 500, since_date=&#39;2021-11-07&#39;)</pre><pre>tweets_df = pd.DataFrame({<br>    &#39;raw&#39; : raw_tweets_list<br>})</pre><p>Here, we will search 500 tweets that contain both ‘Astroworld’ and ‘Travis Scott’ keywords. We set since_date ‘2021–11–07’. All 500 raw tweets are saved in raw_tweets_list. Then, we transform it into the form of a DataFrame tweets_df. Here is what tweets_df looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMLCnL_BS-TX53Qz7qjxzg.png" /><figcaption>A glimpse of raw tweets in tweets_df</figcaption></figure><p>We can save tweets_df for later processes.</p><pre>tweets_df.to_csv(&#39;raw_tweet.csv&#39;, header=True, index=False)</pre><h4>Clean the data</h4><pre>def text_cleaning(text):<br><br>  text = text.lower()<br>  text = text.replace(&#39;\n&#39;,&#39; &#39;) <br>  text = re.sub(r&#39;(@[A-Za-z0-9_]+)&#39;, &#39;&#39;, text)<br>  text = re.sub(r&#39;#[A-Za-z0-9_]+&#39;, &#39;&#39;, text)<br>  text = re.sub(r&#39;https?:\/\/\S*&#39;, &#39;&#39;, text)<br>  text = re.sub(r&quot;[^\w\d&#39;\s]+&quot;,&#39;&#39;, text)<br>  text = re.sub(r&#39;[0-9]+&#39;, &#39;&#39;,  text)<br>  text = re.sub(&#39; +&#39;, &#39; &#39;, text)<br>  text = text.strip()<br><br>  text = text.translate(str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation))<br><br>  text_tokens = word_tokenize(text)<br>  filtered_words = [w for w in text_tokens if not w in stop_words]<br>    <br>  lemmatizer = WordNetLemmatizer()<br>  lemma_words = [lemmatizer.lemmatize(w, pos=&#39;a&#39;) for w in filtered_words]<br><br>  return &quot; &quot;.join(lemma_words)</pre><ul><li>Generally, the above function will remove the unnecessary components from every text in the DataFrame. We make them in a standard format: in lowercase, contain no mentions, contain no hashtags, contain no numbers, contain no punctuations, contain no stop words, etc.</li><li>Next, we also make every word in the text in its basic form.</li></ul><pre>loaded_tweets = pd.read_csv(&#39;raw_tweet.csv&#39;)</pre><p>We reload the saved tweets_df by the name loaded_tweets. Next, we can apply the lambda function for cleaning every row in loaded_tweets.</p><pre>loaded_tweets[&#39;clean&#39;] = loaded_tweets[&#39;raw&#39;].apply(lambda x: text_cleaning(x))</pre><p>Now, loaded_tweets contains both raw and clean data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxaEoyflEJamyeWvpr_aTw.png" /><figcaption>A glimpse of loaded_tweets</figcaption></figure><p>We also drop duplicate rows and save the result in tweets_no_duplicate. Now, we have 308 unique rows.</p><pre>tweets_no_duplicate = loaded_tweets.drop_duplicates(subset=&#39;clean&#39;)</pre><h4><strong>Sentiment Determination</strong></h4><p>Next, we are ready to determine the sentiment of each text in loaded_tweets.</p><pre>def sentiment_determination(tweets_df):<br><br>  tweets_df[[&#39;polarity&#39;, &#39;subjectivity&#39;]] = tweets_df[&#39;clean&#39;].apply(lambda Text: pd.Series(TextBlob(Text).sentiment))<br><br>  for index, row in tweets_df[&#39;clean&#39;].iteritems():<br>    score = SentimentIntensityAnalyzer().polarity_scores(row)<br><br>    if score[&#39;neg&#39;] &gt; score[&#39;pos&#39;]:<br>      tweets_df.loc[index, &#39;sentiment&#39;] = &#39;negative&#39;<br>    elif score[&#39;pos&#39;] &gt; score[&#39;neg&#39;]:<br>      tweets_df.loc[index, &#39;sentiment&#39;] = &#39;positive&#39;<br>    else:<br>      tweets_df.loc[index, &#39;sentiment&#39;] = &#39;neutral&#39;<br><br>    tweets_df.loc[index, &#39;pos&#39;] = score[&#39;pos&#39;]<br>    tweets_df.loc[index, &#39;neu&#39;] = score[&#39;neu&#39;]<br>    tweets_df.loc[index, &#39;neg&#39;] = score[&#39;neg&#39;]<br>    tweets_df.loc[index, &#39;compound&#39;] = score[&#39;compound&#39;]<br><br>  return tweets_df</pre><pre>tweets_df = sentiment_determination(tweets_no_duplicate)</pre><ul><li>For every row in tweets_no_duplicate, we will add two new columns: polarity and subjectivity. These values are returned by TextBlob() which need the cleaned text as the input. Next, using SentimentIntensityAnalyzer().polarity_scores(), we pass the cleaned text as the input. SentimentIntensityAnalyzer().polarity_scores() returns four scores, pos, neg, neu, and compound. We do comparation among those pos, neg, neu scores to determine whether the text is classified as positive, negative, or neutral.</li><li>Now, we have tweets_df as the result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FPwTGFILUZ_2gSmkIDMEg.png" /><figcaption>A glimpse of tweets_df</figcaption></figure><p>Up until now, we have each row with its corresponding label. Let’s take some time to look further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*6bxKXi9UE5IXr9kjRPumgg.png" /><figcaption>Sentiment distribution</figcaption></figure><p>As expected, most of the tweets have negative sentiments. If we plot in pie chart, we can see clearly, the percentage of negative sentiment is 59.74%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*m_4LUD2jNhaZ6VK3aRXbTQ.png" /><figcaption>Sentiment distribution in pie chart</figcaption></figure><p>We have reached our main goal to mine sentiment in the tweets. But for comparing predictive models, there are some additional works to do :).</p><h4>Sentiment Encoding</h4><p>For modeling purposes, we will encode sentiment to numerical representation.</p><pre>def encoded_class(class_string):<br><br>  if class_string == &#39;negative&#39;:<br>    enc_class = 0<br>  elif class_string == &#39;positive&#39;:<br>    enc_class = 1<br>  elif class_string == &#39;neutral&#39;:<br>    enc_class = 2<br><br>  return enc_class</pre><pre>tweets_df = tweets_df[[&#39;raw&#39;,&#39;clean&#39;,&#39;polarity&#39;,&#39;subjectivity&#39;,&#39;pos&#39;,&#39;neu&#39;,&#39;neg&#39;,&#39;compound&#39;,&#39;sentiment&#39;]]<br>tweets_df[&#39;encoded_sentiment&#39;] = tweets_df[&#39;sentiment&#39;].apply(lambda x: encoded_class(x))</pre><h4><strong>Text Vectorizing</strong></h4><p>Computer works with number. So, the next step is to represent text in its numerical representation by applying vectorization.</p><ul><li>For modeling purposes, we put all the clean texts in X and all the labels in y.</li></ul><pre>X = tweets_df[&#39;clean&#39;]<br>y = tweets_df[&#39;encoded_sentiment&#39;]</pre><ul><li>Next, we split the data into training set and testing set.</li></ul><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=2021)</pre><ul><li>Make a DataFrame for training set. We have 163, 66, 48 training data for negative, positive, and neutral sentiment respectively.</li></ul><pre>training = pd.DataFrame({<br>    &#39;text&#39; : X_train,<br>    &#39;sentiment&#39; : y_train<br>})</pre><ul><li>Make a DataFrame for testing set. We have 21, 9, 1 testing data for negative, positive, and neutral sentiment respectively.</li></ul><pre>test = pd.DataFrame({<br>    &#39;text&#39; : X_test,<br>    &#39;sentiment&#39; : y_test<br>})<br><br>test</pre><ul><li>Next, applying vectorization function for both training and testing data. In vectorize the text data, we use TfidfVectorizer(). TfidfVectorizer() converts a collection of raw documents into a matrix of TF-IDF features. TfidfVectorizer() will learn the representation of the training data and transform the testing data based on the learning of the training data.</li></ul><pre>def text_vectorizer(X_train, X_test):<br><br>  tfidf_vectorizer = TfidfVectorizer(use_idf=True, ngram_range=(1,2))<br><br>  X_train_vectorizer = tfidf_vectorizer.fit_transform(X_train)<br>  X_test_vectorizer = tfidf_vectorizer.transform(X_test)<br><br>  return X_train_vectorizer, X_test_vectorizer</pre><ul><li>We apply text_vectorizer() function to X_train and X_test.</li></ul><pre>X_train_vectorizer, X_test_vectorizer = text_vectorizer(X_train, X_test)</pre><h4><strong>Modeling, Cross Validation, Training, and Evaluation</strong></h4><p>After getting our data in vectorized form, we employ them to train and test several models. For each model, we apply the following function. cross_val_score() takes argument cv. Here, we define cv = 5. It means we will make the training set into 5 parts. In the first iteration, the first part will act as a validation set and the remaining are the train set. It continues with the same pattern until the fifth iteration. Then, we will compute the average of the f_1 scores and return it as the output.</p><pre>def modeling_cv_training(model, X, y, cv=5):<br><br>  scorer = make_scorer(f1_score, average =&#39;micro&#39;)<br><br>  cv_scores = cross_val_score(estimator=model, X=X, y=y, cv=cv, scoring=scorer)<br><br>  return np.mean(cv_scores)</pre><p>The following code is the code for evaluating model performance on testing data.</p><pre>def model_metrics(y_true, y_pred, model):<br><br>  print(&#39;Confusion matrix: \n&#39;, confusion_matrix(y_true, y_pred),&#39;\n&#39;) # confusion matrix<br><br>  cm = confusion_matrix(y_true, y_pred, labels=model.classes_)<br>  sns.heatmap(cm, annot=True, fmt=&quot;.1f&quot;, cmap=&#39;cividis&#39;)<br><br>  print(&#39;Classification report: \n&#39;, classification_report(y_true, y_pred),&#39;\n&#39;) # classification report<br>  print(&#39;Precision: {:0.2f}%&#39;.format(round(precision_score(y_true, y_pred, average=&#39;micro&#39;), 4)*100)) # precision<br>  print(&#39;Recall: {:0.2f}%&#39;.format(round(recall_score(y_true, y_pred, average=&#39;micro&#39;), 4)*100)) # recall<br>  print(&#39;F1-Score: {:0.2f}%&#39;.format(round(f1_score(y_true, y_pred, average=&#39;micro&#39;), 4)*100)) # f1-score</pre><p><strong>Multinomial Naive Bayes</strong></p><pre>multinomial_nb = MultinomialNB()<br>cv_score_1 = modeling_cv_training(multinomial_nb, X_train_vectorizer, y_train)<br>cv_score_1<br></pre><p>For Multinomial Naive Bayes, we gain 0.59 as the average of f1_scores.</p><pre>model_metrics(y_test, multinomial_nb.predict(X_test_vectorizer), multinomial_nb)</pre><p>Running this model on the testing set, we get the following results. As we can see, model tends to overfit the first class (negative sentiment). Model fails to detect positive and neutral sentiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*hfXbrBiUGn54Bkra0ePXXg.png" /><figcaption>Results of Multinomial NB</figcaption></figure><p>We also run the same procedure for other models: Gaussian NB, Random Forest, AdaBoost, LGBM, XGBoost, and CatBoost. Overall, Gaussian NB gains the best result among others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*lOJGgoc3rkmTsw5eM2VcZw.png" /><figcaption>All metrics for each model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*TD7waJecdpYrDqthdGI5pQ.png" /><figcaption>Results of Gaussian NB</figcaption></figure><p>Unfortunately, Gaussian NB still shows overfitting. This is somehow understandable. We can see, for the training set, the number of negative sentiments is more than twice the number of positive sentiments. For next improvement, we can acquire more data or do hyperparameter tuning.</p><h4><strong>Word Cloud</strong></h4><p>One might wonder, what words occur more across the tweets. Fortunately, we can visualize it by using WordCloud().</p><pre>def wordcloud(tweets_df):<br>  <br>  mask = np.array(Image.open(your_image_here))<br>  stopwords = STOPWORDS<br><br>  wc = WordCloud(width=1600, height=800,<br>                  background_color=&#39;white&#39;,<br>                  mask = mask,<br>                  stopwords=stopwords,<br>                  repeat=True)<br>  <br>  word = wc.generate(str(&#39;&#39;.join(tweets_df[&#39;clean&#39;])))<br><br>  plt.imshow(word, interpolation=&#39;bilinear&#39;)<br>  plt.axis(&#39;off&#39;)<br>  plt.show()</pre><p>When we call this function, this image is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*ITatsOSKarF-jDo8R9_Zxg.png" /></figure><p>This is interesting, the word ‘tragedy’ tends to appear the most. When we fetch the data from Twitter, we ensure that the fetched tweets contain the words ‘Travis Scott’ and ‘Astrowold’. It can be concluded that the majority of the tweets with those keywords contain the word ‘tragedy’. ‘tragedy’ itself is related to bad things rather than good things. This finally validates our assumption why most of the tweets have negative sentiment.</p><p><strong>Reference:</strong></p><ul><li>CNBC. (n.d.). <em>8 dead, numerous injured at Astroworld Festival in Houston</em>. [online] Available at: <a href="https://www.cnbc.com/2021/11/06/8-dead-numerous-injured-at-astroworld-festival-in-houston.html">https://www.cnbc.com/2021/11/06/8-dead-numerous-injured-at-astroworld-festival-in-houston.html</a> [Accessed 15 Dec. 2022].</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7ee18960a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rock-Paper-Scissors Image Classification with Keras Tensorflow]]></title>
            <link>https://medium.com/@sdwiulfah/rock-paper-scissors-image-classification-with-keras-tensorflow-1c29ba0fe14d?source=rss-3863a0821232------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c29ba0fe14d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Saskia Dwi Ulfah]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 06:50:09 GMT</pubDate>
            <atom:updated>2021-08-28T04:13:05.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sVYm_6A-CtV5Bd6GxlCiLw.jpeg" /><figcaption>[Source: <a href="https://www.playworks.org/colorado/event/playworks-rock-paper-scissors-tournament/">www.playworks.org</a>]</figcaption></figure><p><em>This post is further explanation of rock-paper-scissors image classification project on my Github. Full code can be found </em><a href="https://github.com/saskia-dwi-ulfah/rock-paper-scissors-classification"><em>here</em></a><em>.</em></p><h3><strong>A Brief Concept of Convolutional Neural Network (CNN)</strong></h3><p>In this project, I utilized CNN architecture for classifying image. So, before getting into code explanation, I will briefly explain how this algorithm works.</p><p>CNN is a deep learning algorithm that is commonly used in image classification problems. Generally, this architecture comes in three parts:</p><ol><li><strong>Convolutional layer<br></strong>As it’s name, this layer is the core layer of CNN. This convolutional layer will take an image as <strong>input</strong> in its matrix representation (3-dimensional matrix if it’s a color image, 2-dimensional matrix if it’s a grayscale image). Dot product will be performed between matrix and what is known as <strong>filter</strong>. This process is also known as <strong>convolution</strong>, which aims to detect image features. As the result of the convolution, we have a <strong>feature map</strong>.</li><li><strong>Pooling layer<br></strong>The process in convolutional layer will increase the number of model parameters. Here is where the pooling layer will take a role in reducing the dimensionality of input. Applying a pooling layer will be very beneficial to reduce the risk of overfitting and keep model simple.</li><li><strong>Fully-connected layer<br></strong>In this layer, classification task will be done by computing probability for each classes.</li></ol><h3>Project Explanation</h3><h4><strong>Google Colaboratory: An Interactive Working Environment</strong></h4><p>To work on my code, I would prefer using Google Colaboratory rather than using similar tools. Google Colaboratory is equipped with our needed dependencies, so it won’t take a lot of resources. In addition, it facilitates team collaboration and integrates with Google Drive.</p><h4><strong>Dataset</strong></h4><p>The dataset used in this project is 2188 image data. 1314 images will be used for model training (stored in the <strong>train</strong> folder) and 874 images will be used for model validation (stored in the <strong>validation</strong> folder). In each corresponding folder, there are 3 folders containing scissors, rock, and paper images (<strong>scissors</strong>,<strong> rock</strong>, and <strong>paper</strong> respectively).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*P_y0eBxgPxJheLwd2ZeuuA.png" /><figcaption>Training data and validation data</figcaption></figure><h4><strong>Library</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a2c59f4dcf2a08e0bd1e9f96bf95efd/href">https://medium.com/media/7a2c59f4dcf2a08e0bd1e9f96bf95efd/href</a></iframe><p>First, we need to import the required libraries:</p><ul><li><strong>numpy</strong>, for array-based computation.</li><li><strong>matplotlib</strong>, for visualization and plotting purposes.</li></ul><p>We also import <strong>tensorflow </strong>and <strong>keras </strong>to perform data preprocessing and to define CNN architecture:</p><ul><li><strong>ImageDataGenerator </strong>will be used in data augmentation process.</li><li><strong>Conv2D</strong>, <strong>MaxPool2D</strong>, <strong>Flatten</strong>, <strong>Dense</strong>, and <strong>InputLayer</strong> will define CNN architecture.</li></ul><h4><strong>Image Data Generator</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13128d429d782edfa9cc904402f17f47/href">https://medium.com/media/13128d429d782edfa9cc904402f17f47/href</a></iframe><p>As mentioned earlier, <strong>ImageDataGenerator </strong>class is used in data augmentation process. This technique will extend the size of training data by performing a set of transformations to original images, such as rotation, shifting, flipping, and shearing. This technique will also improve the generalizability of model.</p><p>In this project, a set of transformations that will be used include:</p><ul><li><strong>rescale</strong> : rescale each value in the image matrix representation by multiplying by 1/255. By rescaling, the values in the matrix will range between 0 and 1.</li><li><strong>rotation_range </strong>: apply 30 degrees random rotations.</li><li><strong>shear_range</strong> :<strong> </strong>apply 0.2 shear intensity. That is, shear angle in counter-clockwise direction.</li><li><strong>width_shift_range </strong>: randomly shift image horizontally within a certain range.</li><li><strong>zoom_range </strong>: define random zoom within [0.8, 1.2] range.</li><li><strong>fill_mode </strong>: fill empty area after rotation with the nearest pixel values.</li><li><strong>horizontal_flip </strong>: setting this argument to True means a randomly horizontal flipping will be applied to the inputs.</li></ul><p>After defining <strong>ImageDataGenerator </strong>in <strong>train_datagen </strong>and <strong>validation_datagen </strong>variable, we call <strong>flow_from_directory </strong>method. This method takes the following arguments:</p><ul><li><strong>directory</strong>: this method requires the images to be grouped into different folders (corresponding to their classes) but still in the same parent folder.</li><li><strong>target_size: </strong>size of the input.</li><li><strong>batch_size: </strong>size of batches of data.</li><li><strong>class_mode: </strong>we use ‘categorical’ since we have three classes.</li></ul><h4><strong>Sequential Model</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42261f4a903b013b0059a5a6ebd4f54/href">https://medium.com/media/a42261f4a903b013b0059a5a6ebd4f54/href</a></iframe><p>Next, we construct CNN architecture.</p><ul><li>In the first two lines, we declare <strong>Sequential</strong> model and define <strong>InputLayer </strong>with 150x150x3 input shape for RGB images.</li><li>Next, we define convolutional layer. In this convolutional layer, we use <strong>Conv2D </strong>and <strong>MaxPool2D</strong> alternately. The first argument of <strong>Conv2D </strong>is number of filters that will be applied. Size of each filter is shown in the second argument. For the activation function, we use ReLU, Rectified Linear Unit which introduce a nonlinearity of data to model. Next, <strong>strides </strong>argument specifies the strides of convolution along the height and width. Finally, set <strong>padding </strong>argument to ‘same’ will produce the output with same size as input.</li><li><strong>MaxPool2D </strong>works by taking the maximum value over an input window. Size of this input window is shown in <strong>pool_size </strong>argument. Set <strong>padding </strong>argument to ‘valid’ means we apply no padding. Same as before, set <strong>padding </strong>argument to ‘same’ means the output is same in size as input.</li><li>The output from convolutional layer will be flattened as an input for fully-connected layer. Here is where <strong>Flatten </strong>layer take an action. The hidden layer has 512 nodes with ReLU activation function. For the output layer, we use 3 nodes since we have three classes and Softmax activation function. With this activation function, the probability for each class will be computed and the total of the all probabilities will be 1. The class with the highest probability is the class in which image is classified.</li></ul><h4><strong>Model Compiling and Model Fitting</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80b1e84e4ed136cb7831aae710d8d90b/href">https://medium.com/media/80b1e84e4ed136cb7831aae710d8d90b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*EGnKxevMRerh-yTaMTE7jg.png" /><figcaption>Training and validation loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*dY596whQdQBR7x9Ju2gwOg.png" /><figcaption>Training and validation accuracy</figcaption></figure><p>Once we are done specifying CNN architecture, we will compile and fit the model.</p><ul><li><strong>.compile() </strong>method takes 3 important arguments: <strong>loss</strong>, <strong>optimizer</strong>, and <strong>metrics</strong>. We set ‘categorical_crossentropy’ for the loss function. This loss function is probabilistic losses and is used when we have two or more classes. For the optimizer, we use Adam and metrics of accuracy.</li><li>With <strong>.fit() </strong>method, we will train the CNN model. We train the model with training data which is provided in <strong>train_generator</strong>. As <strong>train_generator </strong>is generator, <strong>y </strong>argument is not required to be specified. <strong>step_per_epoch </strong>(total number of steps before declaring one epoch finished and starting the next epoch) is set to 12. <strong>epochs </strong>(total number of iteration over the entire training data) is set to 32. For <strong>validation_data</strong>, we use <strong>validation_generator </strong>and <strong>validation_steps </strong>(total number of steps to draw before stopping when performing validation at the end of every epoch) is set to 8.</li><li>To be able to observe model learning process, we plot accuracy and loss in each epoch. We expect loss values to decrease and accuracy values to increase as epoch values increase. To do this, we call <strong>.fit() </strong>method in <strong>history</strong> variable. How accuracy and loss plotting is done can be seen in the code above.</li></ul><h4><strong>Predicting Image</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a39a385d5c0592a22146fca22704d6/href">https://medium.com/media/d2a39a385d5c0592a22146fca22704d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*cVGCIt88aA1GR6ESd-nfdA.png" /><figcaption>Predicting image</figcaption></figure><p>Finally! We come to interesting part where model tries to predict unseen image. <strong>.predict() </strong>method produces an output array containing probability for each class. <strong>np.argmax()</strong> will return the index of highest probability in <strong>thing </strong>variable.</p><ul><li>If <strong>thing</strong> is equal to 0, it is <strong>paper.</strong></li><li>If <strong>thing</strong> is equal to 1, it is <strong>rock.</strong></li><li>If <strong>thing</strong> is equal to 2, it is <strong>scissors</strong>.</li></ul><h4>Limitation</h4><p>Unfortunately, this model only shows good performance in predicting unseen image with green background. When it comes to unseen image with no green background, model often to misclassify. This misclassification somehow is understandable since we trained the model with green background images.</p><p><strong>REFERENCE:</strong></p><ul><li><a href="https://www.facebook.com/MachineLearningMastery.">https://www.facebook.com/MachineLearningMastery.</a> (2019, April 11). <em>How to Configure Image Data Augmentation in Keras</em>. Machine Learning Mastery. <a href="https://machinelearningmastery.com/how-to-configure-image-data-augmentation-when-training-deep-learning-neural-networks/">https://machinelearningmastery.com/how-to-configure-image-data-augmentation-when-training-deep-learning-neural-networks/</a></li><li>IBM Cloud Education. (2020, October 20). <em>What are Convolutional Neural Networks?</em> Ibm.com. <a href="https://www.ibm.com/cloud/learn/convolutional-neural-networks">https://www.ibm.com/cloud/learn/convolutional-neural-networks</a></li><li><em>Keras ImageDataGenerator for Image Augmentation | Python Use Case</em>. (2020, August 11). Analytics Vidhya. <a href="https://www.analyticsvidhya.com/blog/2020/08/image-augmentation-on-the-fly-using-keras-imagedatagenerator/">https://www.analyticsvidhya.com/blog/2020/08/image-augmentation-on-the-fly-using-keras-imagedatagenerator/</a></li><li>Keras Team. (2021). <em>Keras documentation: Conv2D layer</em>. Keras.io. <a href="https://keras.io/api/layers/convolution_layers/convolution2d/">https://keras.io/api/layers/convolution_layers/convolution2d/</a></li><li>Keras Team. (2021). <em>Keras documentation: Image data preprocessing</em>. Keras.io. <a href="https://keras.io/api/preprocessing/image/">https://keras.io/api/preprocessing/image/</a></li><li>Keras Team. (2021). <em>Keras documentation: Probabilistic losses</em>. Keras.io. <a href="https://keras.io/api/losses/probabilistic_losses/#categoricalcrossentropy-class">https://keras.io/api/losses/probabilistic_losses/#categoricalcrossentropy-class</a></li><li>Rosebrock, A. (2019, July 8). <em>Keras ImageDataGenerator and Data Augmentation — PyImageSearch</em>. PyImageSearch. <a href="https://www.pyimagesearch.com/2019/07/08/keras-imagedatagenerator-and-data-augmentation/">https://www.pyimagesearch.com/2019/07/08/keras-imagedatagenerator-and-data-augmentation/</a></li><li><em>tf.keras.Model | TensorFlow Core v2.6.0</em>. (2021). TensorFlow. <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model">https://www.tensorflow.org/api_docs/python/tf/keras/Model</a></li></ul><p>‌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c29ba0fe14d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>