<?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 Sushmita Poudel on Medium]]></title>
        <description><![CDATA[Stories by Sushmita Poudel on Medium]]></description>
        <link>https://medium.com/@poudelsushmita878?source=rss-8ef7cf8b0ce7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sushmita Poudel on Medium</title>
            <link>https://medium.com/@poudelsushmita878?source=rss-8ef7cf8b0ce7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:26:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@poudelsushmita878/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[ActionClip: Unifying Vision and Language for Action Recognition]]></title>
            <link>https://medium.com/@poudelsushmita878/actionclip-unifying-vision-and-language-for-action-recognition-fbd94a64639f?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd94a64639f</guid>
            <category><![CDATA[action-recognition]]></category>
            <category><![CDATA[contrastive-learning]]></category>
            <category><![CDATA[video-understanding]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 18:07:54 GMT</pubDate>
            <atom:updated>2024-12-28T06:41:36.226Z</atom:updated>
            <content:encoded><![CDATA[<p>Action recognition in computer vision has emerged as an exciting field that has witnessed significant growth over the past few years. Action recognition, which involves extracting meaningful information from video frames to understand, analyse and recognize dynamic activities of video stream, has been a foundation for various applications, such as video surveillance, healthcare monitoring, human-computer interaction, sports analytics, autonomous driving, and many more. Following the advancements in object detection, image segmentation, recognition, and classification, action recognition has now become a central focus in modern computer vision. Moreover, the rise of vision transformers are powering advancements in action recognition, transforming the shape of video understanding and yielding the best results ever with novel architectures every day.</p><p>Action recognition has marked significant progress over time, evolving from early hand-crafted methods to transformer based models. Here is a brief over-view of its evolution:</p><ol><li><strong>Early Hand-crafted Methods</strong>: Action recognition initially relied on manually engineered features for spatial and temporal information from videos. It involves three steps to do so, i.e feature extraction, feature encoding, and action classification. Histogram of Oriented Gradient (HOG) descriptor captures the edges and gradients of images, and the Histogram of Optical Flow (HOF) extracts the motion feature of objects in an image by computing the components of horizontal and vertical optical flow components respectively, which describes the horizontal and vertical information of object across the frames of a particular video. Features are then encoded into usable representation such as Bag of Visual Words(<a href="https://en.wikipedia.org/wiki/Bag-of-words_model_in_computer_vision">BOW</a>) or higher order statistics (like, <a href="https://en.wikipedia.org/wiki/Fisher_kernel">Fisher Vectors</a>). The encoded features are then passed as an input to traditional classification models like SVM.</li><li><strong>Two-Stream Network</strong>: The introduction of two-stream networks in 2014 by Simonyan and Zisserman proposed the idea of processing spatial and temporal features separately, resulting in the Two-stream ConvNet architecture: Spatial stream and Temporal stream. The spatial stream extracts the features from an image, specifically capturing the static content in the video, while the Temporal stream processes optical flow between frames to capture motion information, showing how objects are moving across the frames. The model was trained on the standard video action benchmark dataset UCF-101 and HMDB-51.</li><li><strong>3D Convolutional Neural Network</strong>: Later, the introduction of 3D CNNs paved the way for further advancements in video understanding by integrating spatial and temporal feature learning into a single network. Unlike 2D CNNs, which convolve over the spatial dimensions of an image, 3D CNNs extend this operation to the temporal dimension by using a 3D kernel. They take a sequence of frames from a video as input, which is represented as a 3D volume (height, width, and depth), with depth corresponding to the number of frames in the sequence. By analyzing adjacent frames together, 3D CNNs learn temporal features, such as the motion of objects.</li><li><strong>Transformer-based Models</strong>: In recent years, transformer-based models have transformed action recognition by leveraging the self-attention mechanism to effectively capture the long-range depecdencies across spatial and temporal dimensions. Unlike traditional CNN architectures, these models treat video as a sequence of patches, enabling them to model spatial and temporal relationship combined. This innovation has led to the state-of-the-art performance in video understanding task, making transformers a powerful tool for understanding complex dynamic action in videos.</li></ol><p>As of now, numerous transformer based models have been introduced, many of which achieve state-of-the-art performance on benchmark dataset such as <strong>Kinetics-400</strong>. Key examples include <strong>Timesformer</strong>, <strong>Uniformer</strong>, <strong>VideoMAE</strong>, which have significantly advanced the field with their ability to process spatio-temporal data efficiently.</p><p>While significant progress in action recognition have been made through various architectures, one model that stands out for its innovative approach is <strong>ActionCLIP</strong>, introduced in 2021. By combining language and vision modalities, it seeks to understand complex patterns in the video and has opened up new possibilities in video understanding research.</p><p>ActionClip is an extended form of <strong>OpenAI</strong>’s <strong>CLIP (Contrastive Language-Image Pretraining)</strong> architecture, which learns visual representation of an image through language supervision. CLIP, trained on millions of video-text pairs collected from internet, bridges the gap between vision and language by jointly training the model on a large scale dataset containing image along with their textual description. It achieves this by leveraging a vision encoder to process visual data and text encoder to process textual inputs, matching both in a shared embedding space. Building on the foundation of CLIP, ActionCLIP distinguishes itself from other transformer-based models through its unique approach of learning and understanding videos, recognizing actions with enhanced contextual awareness.</p><h4>Architecture Overview</h4><p>Below is the general overview of how ActionCLIP actually works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Kcn_XD_nWJ6fT70Ad8bfzw.png" /><figcaption>Figure 1: Traditional Unimodal vs. Multi-modal Framework for Action Recognition (Image source: <a href="https://arxiv.org/pdf/2109.08472">paper</a>)</figcaption></figure><p>The above figure demonstrates the architecture of both unimodal and multimodal models for action recognition. As illustrated in the figure (b) above, ActionCLIP takes two inputs: a video and the corresponding textual description associated with that particular video clip. The architecture consists of two main components:: the<strong> text encoder</strong> (transformer-based language models) and the <strong>video encoder</strong> (vision transformers), along with an embedding space.</p><ol><li><strong>Video Encoder</strong>: The video encoder in ActionCLIP is designed to handle spatio-temporal data. Based on the CLIP’s video encoder, it processes video input by dividing them into a grid of tubelets — small 3D segments that capture information across spatial and temporal dimension. Each tubelet is flattened into a vector and passed though a layer to create embeddings, known as <strong>Tubelet Embeddings</strong>. These embeddings effectively combine spatial (appearance) and temporal (motion) features, allowing the model to understand <em>what happens in the video </em>and<em> how it changes over the time</em> effectively.</li><li><strong>Text Encoder</strong>: It is a transformer-based language model, adapted from CLIP’s text encoder, that processes the textual description and generates an embedding which captures the context, syntax, and meaning of the text.</li><li><strong>Shared Embedding Space</strong>: The shared embedding space is the core of the ActionClip’s multimodal functionality, enabling interaction between image and text modalities. Both encoders produces embedding of the same dimension and are projected into this shared latent space, ensuring proper alignment. Cosine similarity is then used to compare the video and text representations. Matching pairs have their cosine similarity maximized, while non-matching pairs have their cosine similarity minimized. And during training, the model is optimized to maximize the similarity for matching pairs and minimize it for non-matching pairs, learning their underlying relationship.</li></ol><h4>Contrastive Learning and Training Process</h4><p>ActionCLIP utilizes <strong>Contrastive learning</strong> to effectively align video and text representation in the shared embedding space. The goal of contrastive learning is to bring the embeddings of matching video-text pair closer together while pushing the embeddings of mismatched pairs apart. This is achieved by minimizing <strong>contrastive loss function</strong> which measures the distance between the embeddings of video and text modalities. Contrastive loss function penalizes the model for incorrectly matching pairs and rewards it for correctly matching pairs in latent space. ActionCLIP specifically uses <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">KL divergence</a> as the contrastive loss function.</p><p>During training, the model is presented with a pair of video clips and their textual descriptions. And through contrastive learning, the model learns to capture the semantic relationship between the visual and textual inputs. For instance, when a video of a soccer goal is paired with the description “scoring a goal”, the model learns to place the embeddings of both the text and video closer together in the shared space. Conversely, it learns to distinguish the embeddings for unrelated video-text pairs.</p><p><strong>How the model learns to make embeddings meaningful?</strong></p><ul><li>Starts with random embeddings: The embeddings from both the video<em> </em>and text encoders are random at first, to avoid ambiguity. For example: a video of a baby crawling on the floor and the text “baby crawling” will have embeddings that don’t meaningfully align. At this stage, the embeddings generated by both encoders are not representing anything useful because they’re generated randomly, and the cosine similarity between video and text will yield random or low values.</li><li>Uses labelled data: During training, the model is presented with labelled data, i.e. pair of video and its corresponding textual information (eg: video of a baby crawling paired with the text “baby crawling”). The model learns that these pairs should be close to each other in the embedding space. The label guides the model in identifying which pairs are related.</li><li>Uses Contrastive loss: It uses contrastive loss that encourages the model to bring the embeddings of matching video-text pairs closer together and push the embeddings of non-matching pairs further apart. If the similarity between a matching pair is too low, the model is penalized and learns to increase the similarity; and if the similarity between non-matching pair is too high, again the model gets penalized and forcing the model to distinguish it better.</li><li>Learns through feedback: After each training iteration, the model receive feedback on how accurate embeddings are. When the model gets the embedding misaligned (e.g., the video of a baby crawling and the text “baby crawling” are too far apart), it adjusts its parameters to improve the next embedding generation. Over the time, this feedback helps the model to generate meaningful embeddings where videos and their matching text are closer together, and non-matching text and videos are far apart.</li></ul><h4><strong>Detailed Illustration of ActionCLIP Architecture and Prompt Modules</strong></h4><p>ActionCLIP uses prompt based learning — using specific instructions to guide the learning process — by incorporating three types of prompt: pre-network prompt, in-network prompt, post-network prompt. These techniques help the model to better understand the video content by aligning it with semantic context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4hYameCFv3jmDOXkOr3og.png" /><figcaption>Fig 2: Detailed Architecture of ActionClip (Image Source: <a href="https://arxiv.org/pdf/2109.08472">paper</a>)</figcaption></figure><ol><li><strong>Pre-network Prompt</strong>: This prompt provide guidance to the model before the actual video is processed, setting the expectation for the task. For example, a prompt like “The player is scoring a goal in the soccer match” helps the model focus on motion relevant to that action.</li><li><strong>In-network Prompt</strong>: During video processing, this prompt adjust the model’s attention to specific features in the video. Through the embeddings of tokens (eg: score goal, kick, pass) within the model’s layer, it helped maintain focus on the most relevant frames for action recognition.</li><li><strong>Post-network Prompt</strong>: After processing, the post-network prompt refines the models output by adding more context, ensuring the final action is accurately labelled, such as “scoring a goal”, “passing the ball” or “baby crawling”.</li></ol><p>Also, the prompt in ActionCLIP can be passed in three formats, which help the model capture a variety of semantic relationships between text and video, as shown in Figure 2(b). Using multiple prompt styles makes the model less sensitive to the specific phrasing of inputs. The formats are as follow:</p><ul><li>Prefix Prompt: Begins with the label. For e.g., “<strong>[label]</strong>, a video of action”</li><li>Cloze Prompt: Label embedded in the middle of the prompt. For e.g., “This is <strong>[label]</strong>, a video of action”</li><li>Suffix Prompt: Places the label at the end of the prompt. For e.g., “A video of action<strong> [label]</strong>”</li></ul><h4><strong>Performance on Benchmark Dataset</strong></h4><p>It has achieved state-of-the-art performance on benchmark dataset kinetics-400 dataset. This dataset consists of 400 different kind of human actions which serves as a standard for training and evaluating action recognition models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*YQO-uMCvhzSCWcKEtV8mzg.png" /><figcaption>Table 1: Performance comparison of various models with ActionCLIP on Kinetics 400 dataset. (Source: <a href="https://arxiv.org/pdf/2109.08472">paper</a>)</figcaption></figure><h4>Zero-Shot Prediciton:</h4><p>ActionCLIP has an ability of zero-shot prediction, which means the model is presented with a video clip and a set of text labels of has never seen before and predict the correct label among the provided set. This is achieved because, during training, the model does not simply learn to recognize specific video or text, instead it focus on developing a general understanding of visual and textual concepts, which enables it to adapt to new tasks and labels without additional training.</p><p>ActionCLIP performing zero-shot prediction on the video below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXUNPKMmQin1rbdIwrVkdA.png" /><figcaption>Player kicking a ball. (Video Source: <a href="https://www.istockphoto.com/video/girls-soccer-team-practicing-to-shoot-for-goal-gm1359680092-432942554?utm_source=pixabay&amp;utm_medium=affiliate&amp;utm_campaign=SRP_video_sponsored_ratiochange&amp;utm_content=https%3A%2F%2Fpixabay.com%2Fvideos%2Fsearch%2Fa%2520girl%2520playing%2520soccer%2F&amp;utm_term=a+girl+playing+soccer">pixabay</a>)</figcaption></figure><p><a href="https://www.istockphoto.com/video/girls-soccer-team-practicing-to-shoot-for-goal-gm1359680092-432942554?utm_source=pixabay&amp;utm_medium=affiliate&amp;utm_campaign=SRP_video_sponsored_ratiochange&amp;utm_content=https%3A%2F%2Fpixabay.com%2Fvideos%2Fsearch%2Fa%2520girl%2520playing%2520soccer%2F&amp;utm_term=a+girl+playing+soccer">Practicing to shoot for goal. Shot from behind the goal net.</a></p><pre># This inference code can be found in mmaction repo, I took it from there<br>import mmengine<br>import torch<br>from mmaction.utils import register_all_modules<br>from mmaction.apis import inference_recognizer, init_recognizer<br><br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>register_all_modules(True)<br><br>config_path = &#39;/path/to/mmaction2/projects/actionclip/configs/actionclip_vit-base-p32-res224-clip-pre_1x1x8_k400-rgb.py&#39;<br>checkpoint_path = &#39;https://download.openmmlab.com/mmaction/v1.0/projects/actionclip/actionclip_vit-base-p32-res224-clip-pre_1x1x8_k400-rgb/vit-b-32-8f.pth&#39;<br># template = &#39;The woman is {}&#39;<br>labels = [&#39;Jumping&#39;, &#39;passing ball&#39;, &#39;scoring goal&#39;, &#39;playing tennis&#39;]<br><br># Update the labels, the default is the label list of K400.<br>config = mmengine.Config.fromfile(config_path)<br>config.model.labels_or_label_file = labels<br># config.model.template = template<br><br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model = init_recognizer(config=config, checkpoint=checkpoint_path, device=device)<br><br>pred_result = inference_recognizer(model, &#39;/home/fm-pc-lt-273/projects/cricket_action_recognization-main/istockphoto-1359680092-640_adpp_is.mp4&#39;)<br>probs = pred_result.pred_scores.item<br><br># index of the highest probability<br>max_index = probs.argmax()<br>max_prob = probs[max_index]<br>predicted_label = labels[max_index]<br><br>print(f&quot;Predicted label: {predicted_label}, Conf: {max_prob * 100:.2f}%&quot;)<br><br><br>## Output::<br>## Predicted label: scoring goal, Conf: 94.51%</pre><p><a href="https://github.com/open-mmlab/mmaction2/tree/main/projects/actionclip"><strong>MMAction2</strong></a>, a popular open-source toolbox for video understanding tasks, includes an implementation of ActionCLIP. It provides easily reusable and modular code, enabling users to train the model on custom datasets and perform inference effortlessly.</p><p>This article has provided you with an overview of the evolution of action recognition in computer vision, along with the architecture and inner workings of ActionCLIP. For a more detailed understanding of its workflow, I recommend exploring it’s codebase in its <a href="https://github.com/sallymmx/ActionCLIP">official repository</a> or on MMAction2 repo.</p><p>References:</p><p><a href="https://ieeexplore.ieee.org/document/7846652">https://ieeexplore.ieee.org/document/7846652</a></p><p><a href="https://arxiv.org/pdf/2109.08472">https://arxiv.org/pdf/2109.08472</a></p><p><a href="https://viso.ai/deep-learning/clip-machine-learning/">https://viso.ai/deep-learning/clip-machine-learning/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd94a64639f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift]]></title>
            <link>https://medium.com/@poudelsushmita878/batch-normalization-accelerating-deep-network-training-by-reducing-internal-covariate-shift-f423360408ae?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f423360408ae</guid>
            <category><![CDATA[covariate-shift]]></category>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[internal-covariate-shift]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 07:05:34 GMT</pubDate>
            <atom:updated>2024-12-14T08:14:00.649Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep Learning has revolutionized various fields, including computer vision to natural language processing, and many more. However, training deep neural network remain complicated by the fact that the distribution of each layer’s input changes during training as the parameter of it’s previous layers change. This phenomenon, which makes it hard to train deep neural network with saturating non-linearity, is termed as <strong>Internal Covariate Shift</strong>.</p><h4><strong>Understanding Internal Covariate Shift</strong></h4><p>Before understanding internal covariate shift, we first need to understand what covariates and covariate shift are.</p><p><strong>Covariates</strong> are features that influence the outcome of a given statistical trial but are not the primary variables of interest. In the context of machine learning, covariates are input features or variables that affect the model’s outcome but are not the primary output or target.</p><p><strong>Covariate shift</strong> occurs when the statistical distribution of input features changes between the training and testing phases of a machine learning model. This means that the data model sees during training is not a representative of the data it will encounter during testing.</p><p>For example, consider training an action recognition model using video data from daytime football matches and testing the model on video data from nighttime matches, here the shift in data distribution from day to night can lead to model performance degradation. The model may struggle to generalize because it has learned patterns specific to daytime conditions that do not apply to nighttime conditions. Similarly, a speech recognition model trained on British accent data and tested on American accent data would face similar issues. Another example is a medical diagnosis model trained on samples from an age group of 1 to 20 years and tested on samples from an age group up to 60 years. Such changes in data distribution may lead to poor model generalization ability.</p><p><strong>Internal covariate shift</strong> is a phenomenon in deep neural networks where the distribution of activations within a network’s layer changes during training. The distribution of activations refers to the statistical properties, such as mean and variance, of the outputs of neurons within a layer of the network. This change occurs as the network’s parameters, i.e. weights, are updated iteratively through processes like backpropagation and each layers need to continuously adapt the changing distribution of data from previous layers. This can make it harder for the network to learn effectively, which is why techniques like <strong>Batch Normalization</strong> are used to mitigate this issue by stabilizing the distributions of layer activations. The authors Sergey Ioffe and Christian Szegedy defined it as follows:</p><blockquote>Internal Covariate Shift is the change in the distribution of network activations due to the change in network parameters during training.</blockquote><p>The following figure (Fig 1 &amp; 2) demonstrates the concept of internal covariate shift across two iterations in a deep neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgWc_42_k6WT5MWmLkyztg.png" /><figcaption>Figure 1: Internal Covariate Shift — Iteration 1</figcaption></figure><figure><img alt="The diagram highlights how internal covariate shift occurs as the distribution of activations changes across different layers due to iterative updates in the network’s parameters. This shift complicates the learning process, causing slower convergence and presenting challenges in achieving effective generalization." src="https://cdn-images-1.medium.com/max/1024/1*ELv3qXF0dvTL2WEf1zCjaw.png" /><figcaption>Figure 2: Internal Covariate Shift — Iteration 2</figcaption></figure><p>If we examine the figures above, we observe that the data distribution in hidden layer 1 differs between Iteration 1 and Iteration 2. Similarly, the distributions of layers 2, k, k-1, and n also show variations between these two iterations.</p><p>Before passing data through a neural network, we often normalize it to have a mean of 0 and a standard deviation of 1. However, as this data moves through the network’s layers, each neuron’s weights and biases transform it, causing the distribution of the data to shift. This shift, known as internal covariate shift, is the change in the distribution of layer inputs during training. Moreover, when training with mini-batches of data (e.g., a batch size of 32), each batch can have a different distribution. For example, in a dataset used to predict car prices, one batch might contain data of affordable cars like Maruti Swift, while another batch includes luxury cars like Rolls-Royce. These differences mean that the network encounters varying data distributions in each iteration, making it harder to learn and adapt efficiently. This continuous adjustment to new distributions slows down the training process and can lead to instability.</p><p>So to address the problem of internal covariate shift and accelerate the training of deep neural networks, in 2015, researchers <em>Sergey Ioffe</em> and <em>Christian Szegedy</em> introduced a novel approach called<strong> Batch Normalization</strong>.</p><h4>What is Batch Normalization?</h4><p><strong><em>Batch normalization</em></strong><em> (also known as </em><strong><em>batch norm</em></strong><em>) is a method used to make training of artificial neural network faster and more stable through normalization of the layers’ inputs by re-centering and re-scaling. </em><a href="https://en.wikipedia.org/wiki/Batch_normalization"><em>Wikipedia</em></a><em>.</em></p><p>Normalizing input data is crucial for optimization algorithms like gradient descent to converge faster. If input data is not normalized, inputs with different scales can result in uneven gradients, which slows down the convergence. Normalization helps maintain consistent gradient flow and ensures numeric stability. Batch normalization extends this idea by normalizing the output of neurons within each layer, which helps in speeding up the training process and improving the model’s performance. It is typically applied after linear transformation and before activation functions in neural network.</p><p>In the following equation and figure, we see how batch normalization is integrated into a neural network.</p><p><strong>𝑦 =∑𝑥𝑖𝑤𝑖+𝑏</strong> — — — — — — — — — — — —- — — — — Linear Transformation<br><strong>bn = (BN(y))</strong> — — — — — — — — — — — — — — -— Batch Normalization<br><strong>z = 𝑓(bn)</strong> — — — — — — — — — — — — — — — — -— Non-linear Transformation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fdu83WHenSnay7knkNbsxw.png" /><figcaption>Fig 2: Neural Network with Batch Normalization. Image by Author</figcaption></figure><p><strong>How Batch Normalization Works?</strong></p><p>Batch normalization reduces the effect of internal covariate shift and accelerate the training of deep neural networks, while also providing additional benefits like improved generalization and reduced sensitivity to parameters initialization, such as weights and learning rate, in two steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*pjdowrOpJMO6mJWS0lYbFA.png" /><figcaption><strong>Algorithm 1:</strong> Batch Normalization, applied to activation x over a mini-batch. <a href="https://arxiv.org/pdf/1502.03167">From research paper</a></figcaption></figure><ol><li><strong>Input standardization</strong><br>During training, batch normalization computes the mean and standard deviation for each mini-batch. For instance, if the batch size is 32, in every iteration 32 samples will be propagated forward and backward through the network. In forward propagation, batch normalization will first calculate the stats like mean and standard deviation for those mini-batch samples and then utilizes these computed stats to standardize each input samples. The mathematical equation detailing this process can be found in the first three equations of Algorithm 1. The epsilon (ε) symbol in the third equation ensures numerical stability. If the standard deviation were to equal zero, the normalized <em>X̂</em> would result in an infinite value, which is not practically feasible. Therefore, epsilon, a very small value, is added to prevent this issue.</li><li><strong>Scaling and Shifting</strong><br>In step 1, the data is adjusted to have a mean of 0 and a variance of 1, ensuring that the data fed into each layer has consistent statistical properties. While normalization is beneficial, it constrains the data within a narrow range. This constraint can reduce the network’s ability to learn diverse patterns, as it limits the variability of the original data by normalizing the inputs. In simpler terms, the non-linearity of the data might be reduced. So, for a model to learn effectively, different layers of the network might need different statistical properties to capture complex data patterns. To address this, the authors of the batch normalization paper introduced two new learnable parameters: γ (scale) and β (shift). These parameters allow the network to adjust the normalized data to a different range that might be more suitable for learning. Refer to the last equation in Algorithm 1 for the mathematical calculations involving scale and shift, as shown below:</li></ol><p>y = γX̂ᵢ + β</p><p>Look at the figure below to clearly understand the working steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JLAPk5iA90hC8TGhs35tg.png" /><figcaption>Fig 3: Illustration of Batch Normalization Steps</figcaption></figure><p>Now you might be curious about how the network learns the parameters γ (gamma) and β (beta). During training, each neuron in the network observes the data patterns over many iterations and across different batches. The kind of distribution it results in is influenced by the specific data patterns each neuron encounters during these iterations. The values of γ and β are adjusted during training using back propagation and gradient descent, similar to other learnable parameters in the network. This process allows the network to fine-tune the scale and shift of the normalized data, optimizing the input distribution for each layer to enhance learning and model performance.</p><p>Though the authors of the paper recommend applying batch normalization between the linear transformation and non-linear activation function, there are numerous debate ongoing in the internet regarding the optimal placement of batch normalixation—before or after activation function. Some poeple argue that batch normalization should be applied after activation function to normalize the output range changed by the activation function and others agree with the author of the paper, saying it should be placed before activation to keep input values consistent across layers. For further insight you can refer to this <a href="https://stackoverflow.com/questions/34716454/where-do-i-call-the-batchnormalization-function-in-keras">thread</a>.</p><p>If you found the article helpful, show your support by clapping and share it with others who might find it helpful. Any feedback would be greatly valued. Thank you for reading.</p><p>References:</p><p><a href="https://arxiv.org/pdf/1502.03167">https://arxiv.org/pdf/1502.03167</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f423360408ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Generative Adversarial Networks (GANs)]]></title>
            <link>https://medium.com/@poudelsushmita878/exploring-generative-adversarial-networks-gans-ae9784ec1a49?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9784ec1a49</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 05:29:42 GMT</pubDate>
            <atom:updated>2024-09-09T05:34:01.024Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building fake realities with the science and art of GAN</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hU4_pkdmijtzLsVTnaK38A.jpeg" /><figcaption>Two robots playing chess depicting Generative Adversarial Networks (GANs), symbolizing the generator and discriminator working together. <a href="https://stock.adobe.com/images/the-picture-depicts-generative-adversarial-networks-gans-with-two-robots-playing-chess-symbolizing-generator-and-discriminator-working-together-version-2/568011144">Image Source</a></figcaption></figure><p>In the ever-evolving landscape of artificial intelligence, neural networks have emerged as a keystone, revolutionizing advancements in various domains such as computer vision, natural language processing, and data science. Innovations in machine learning have advanced to the point where models can perceive and propose solutions to real-world problems. These advancements enable AI to tackle complex issues, from healthcare diagnostics to autonomous driving, offering state-of-the-art solutions and transforming industries. With the ability to understand and address human challenges, machine learning continues to push the boundaries of what is possible, making significant contributions across various fields.</p><p>With the continuous progress in neural networks, scientists have developed many novel approaches that have significantly enriched the capabilities of artificial intelligence. Among these advancements, generative models stand out for their ability to create remarkably realistic data. These models are designed to learn and generate new data that closely resembles the data they were trained on.</p><p>One prominent type of generative model is the Generative Adversarial Network (GAN), a deep learning architecture pioneered by Ian J. Goodfellow and his colleagues in 2014. GANs have introduced a new direction for synthetic data generation, art creation, and beyond. Despite achieving significant success in modeling machines to accomplish tasks in a human-like or more intelligent manner, data scarcity remains a common challenge in the sphere of machine learning. GAN helps to overcome this by generating synthetic data, thereby significantly expanding the potential of artificial intelligence and machine learning. In this article, we will explore everything about GAN in detail.</p><h4>Introduction</h4><p>GAN, as a generative modeling approach, learns the underlying distribution of input data and generates new data samples that resembles the training data. It consists of two main components: a generator and a discriminator, trained adversarially, to produce realistic data. In this setup, the two segments of the network compete with each other in a zero-sum game where the gain of one part comes at the loss of the other. This tug-of-war between the generator and discriminator forms the heart of the GAN training process.</p><h4>Analogy for Better Understanding</h4><p>To understand this dynamic interaction between the two segments of a GAN, imagine a novice potter (the generator) continuously trying to create a bowl from clay and presenting it alongside an already existing artistic bowl to an expert potter. The expert potter (the discriminator) criticizes every attempt of the novice potter by comparing the created bowl with the perfect artistic bowl. With each attempt, the novice potter strives to create a better bowl, while the expert potter tries to find even minor mistakes. As this process continues, the novice potter refines his skill to create an artistic bowl, while the critic refines his ability to identify fine details. This is how GANs work.</p><h4>GAN Architecture</h4><p>Simple illustration of how both segment of GAN works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*_nm1ObT-C13oR2tpnBf4og.png" /><figcaption>Fig 1: GAN Architecture. <a href="https://www.kdnuggets.com/2017/01/generative-adversarial-networks-hot-topic-machine-learning.html">Image source</a></figcaption></figure><h4>Components of GAN</h4><ol><li><strong>Generator</strong>: This network takes random noise as an input and generates synthetic data sample. Although it starts with noise, its goal is to generate realistic samples that are indistinguishable from real data samples from training set.</li><li><strong>Discriminator</strong>: This segment tries to distinguish between real data samples and fake data (those generated by the generator). It’s objective is to correctly identify the real sample and generator generated synthetic dataset.</li></ol><h4>Adversarial Process</h4><p>The adversarial process of — generator trying to fool the discriminator by generating more realistic sample from noise and discriminator getting better at distinguishing real sample from fake over the time continues iteratively until the generator produces high-quality data that is nearly indistinguishable from real data. To better understand the adversarial process, let’s delve into how each component’s loss function guides this adversarial training and ensures the generator and discriminator improve over time.</p><h4>Notations</h4><p>Before we discuss the loss functions and training process, let’s once look at the notations we will use on later sections.</p><ul><li><em>z</em>: Noise vector sampled from the prior distribution <em>p𝓏(z)</em> in the latent space.</li><li><em>p𝓏(z)</em>: Prior distribution of the latent noise vector z, from which z is sampled.</li><li><em>G(z; θ</em>𝓰<em>)</em>: Generator function that maps the input noise <em>z</em> to data space <em>x</em>. Here, θg​ represents the parameters (weights and biases) of the generator network.</li><li><em>x</em>: Data sample, which can be either a real data sample from the training dataset or a synthetic data sample generated by the generator.</li><li><em>p𝒹ₐₜₐ</em>​(x): Real data distribution from which the training data samples <em>x</em> are drawn.</li><li><em>p</em>𝓰<em>(x)</em>: Distribution of the synthetic data generated by the generator.</li><li><em>D(x; θ𝒹)</em>: Discriminator function that takes a data sample <em>x</em> as input and outputs a scalar value representing the probability that <em>x</em> is a real data sample. Here, <em>θ𝒹 ​</em> represents the parameters (weights and biases) of the discriminator network.</li></ul><h4>Loss Functions and Training</h4><p>Now let’s see how the generator and discriminator loss is computed:</p><ol><li><strong>Discriminator</strong>: Once synthetic data generated by generator, the discriminator function <em>D(x; θ𝒹)</em> takes a data sample <em>x</em> as an input and outputs a scalar value <em>D(x) </em>which<em> </em>represents the probability that the input data sample <em>x</em> came from the real probability distribution (real training sample) rather than from the generator’s (G) distribution <em>p𝓰</em>. The discriminator is trained to maximize,<em>D(x)</em>, its ability to differentiate between the real and generated data samples. The loss function for discriminator is as follows:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*nPrCQuP8_QjLp_ftuY59rA.png" /></figure><p>where, the first part of the loss <em>LD</em> represents the logarithm of probability assigned by the discriminator to real data sample <em>x</em> — it gives the ability of discriminator to correctly classify real sample as real, while the second part is the probability assigned by discriminator to generated data sample <em>G(z) </em>— which represents the ability of discriminator to correctly classify generated sample as fake.</p><p>Let’s further breakdown the expression to better grasp the mathematics behind it,</p><ul><li><em>x∼p𝒹ₐₜₐ</em> denotes that <em>x</em> is sampled from the real data distribution <em>p𝒹ₐₜₐ</em>.</li><li>D(x) is the probability of discriminator correctly classifying real sample as real<em>; 0 </em>≤ <em>D(x) </em>≤ 1.</li><li>when <em>D(x) -&gt; 0, log(D(x) -&gt; 1</em><br> <em>D(x) -&gt; 1, log(D(x) -&gt; 0</em></li><li><em>z∼ p𝓏</em>​<em>(z)</em> denotes that <em>z</em> is sampled from the distribution <em>p𝓏</em>​<em>(z).</em></li><li><em>G(z)</em> are samples generated by G using noise <em>z.</em></li><li><em>D(G(z))</em> is output probability of discriminator for the generated sample <em>G(z); 0 </em>≤ <em>D(G(z)) </em>≤ 1.</li><li>when <em>D(G(z)) -&gt; 0, (1-D(G(z))) -&gt; 1</em> and <em>log(1-D(G(z))) -&gt; 0</em><br> <em>D(G(z) -&gt; 1, (1-D(G(z))) -&gt; 0</em> and <em>log(1-D(G(z))) -&gt; 1</em></li><li>The expectation <strong><em>E</em></strong>ₓ and <strong><em>E</em></strong>𝓏 is to calculate the average of log probabilities over the entire distribution of real data sample and noise <em>z </em>respectively. Discriminator attempts to maximize both.</li></ul><p><strong>2. Generator</strong>: It takes noise vectors <strong><em>z</em></strong><em> </em>as an input from a prior distribution <em>p𝓏(z) </em>in the latent space, latent space is space of all possible inputs that can be given to the generator network, each point in latent space represents a different set of input parameters that can be fed into generator. The generator function, represented as <em>G(z; θ𝓰)</em>, then maps the input noise <em>z</em> to data space <em>x.</em> Simply put, generator transforms random noise <em>z</em> into synthetic data <em>x</em>. In the match of creationn and critique, generator is trained to produce samples that discriminator classifies as real, minimizing discriminators ability to correctly differentiate between real and generated samples, minimizing following terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*sb4ATYCaxrq69IzOCjMCsw.png" /></figure><p>Putting the loss function for both generator and discriminator altogether, final loss function to be optimized is formed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvgWR45MBeoYkeJQZPt39w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*jzxc9Bu1uSwYfiZp-kRz9g.png" /></figure><h4>GAN Evaluation Metrics:</h4><ol><li><strong>Inception Score (IS)</strong>: It measures the quality and diversity of the generated images based on the inception model. It is calculated by taking the exponential of the Kullback-Leibler (KL) divergence between the conditional label distribution p(y/x) and marginal label distribution p(y). Higher inception score indicates that the generated images are more realistic and diverse.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*03qnWsVzakID6yTAkzSi-w.png" /></figure><p>where, KL(p(y∣x)∥p(y)) is the KL divergence between conditional distribution p(y∣x) and marginal distribution p(y). KL divergence measures how one probability distribution is different from second, reference probability distribution.The conditional probability distribution p(y/x) for a given generated image x is the probability distribution over possible class labels generated by the Inception model, indicating how likely it is that the image belongs to each class. Marginal distirbution is average probabilities of these labels across all generated images.</p><p>2. <strong>Fréchet Inception Distance (FID)</strong>: It measures the similarity between the real and generated samples based on the feature extracted by Inception network. It calculates Fréchet distance between the feature distribution of real and generated data samples. Lower FID score represents that the generated image is closer to the real image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*jxBLKWxPo7mlvAnNyy31SA.png" /></figure><p>where, Tr denotes the trace of a matrix, which is the sum of its diagonal elements. μr​ and Σr are mean and covariance extracted from real images. Similarly, μg​ and Σg are mean and covariance extracted from generated images.</p><h4>Variety of GAN:</h4><ol><li>Vanilla GAN<br>It refers to the original GAN architecture proposed by Goodfellow and his colleagues in 2014. It simply has a generator and a discriminator network. It has provided a fundamental understanding of how adversarial learning can be used for generative modelling.</li><li>Conditional GAN (CGAN)<br>Conditional GAN (CGAN) is an extension of GAN that incorporates conditional information to both discriminator and generator network. This additional information can be in the form of label or other relevant data which allows GAN to generate data which is conditioned on this information. In this, generator takes random noise(<em>z</em>) as an input along with the conditional information(y), similarly, discriminator takes the both data sample(real and fake) and the conditional information(<em>y</em>). By conditioning on auxiliary information, CGAN provides control over the data generation.</li><li>Deep Convolutional GAN (DCGAN)<br>In DCGAN, both the discriminator and generator network uses convolutional neural network. It replaces the fully connected layers with convolutional layers which helps in capturing the spatial hierarchy in images to enhance the quality of the generated images, which makes it suitable tasks such as image generation.</li><li>Cycle GAN<br>Cycle GAN is designed for unpaired image-to-image translation. Unlike other GAN that require paired examples (for eg: a set of images and their corresponding generated images), cycle GAN can learn to translate images without paired data. It consists of two generator and two discriminator. One generator translates image from domain A to B, and another generator translates them back from domain B to A. And it ensures that the image translated to another domain and back to original domain remains similar to the original image. Can be used in applications like: style translation, image synthesis.</li><li>Style GAN<br>Style GAN, introduced by NVIDIA, focuses on generating high-quality images with control over the generated image’s style. It uses “style-based” generator architecture which has a mapping mapping network that maps the input latent code into an intermediate latent space, which controls the style of the generated images. It can be used for high quality artistic content creation.</li><li>Wassertian GAN (WGAN)<br>It is an another type of GAN that aims to improve the stability of learning, get rid of problems like mode collapse, and and provide meaningful learning curves useful for debugging and hyperparameter searches.[<a href="https://en.wikipedia.org/wiki/Wasserstein_GAN">wikipedia</a>]</li></ol><h4>GAN Limitations</h4><p>Even though GANs have gained significant popularity for their ability to generate realistic images, they impose several major limitations and challenges.</p><ol><li><strong>Unstable Training</strong>: Due to their adversarial training process, training GANs to reach an equilibrium point where the losses for both the generator and the discriminator network are minimized is notoriously difficult.</li><li><strong>Mode Collapse</strong>: GANs can experience model collapse when the generator network generates the same outputs, failing to represent a diverse data distribution. This issue can hinder the effectiveness of GANs in generating realistic and high quality outputs.</li><li><strong>Interpretation Difficulties</strong>: There are no comprehensive metrics that capture all aspects of a model’s performance to evaluate the GANs which complicates the process of improving and assessing the model’s output. Though there are metrics like Inception Score (IS), Frechet Inception Distance (FID) but they may not fully capture all aspects of GAN’s performance.</li><li><strong>Ethical Concerns</strong>: With their ability to produce high-quality and realistic outputs, GANs come with a risk of geenerating fake data and spreading misinformation. The false data generated by GAN can be used to deceive world in digital media.</li></ol><h4>Implementation</h4><p>1. Import dependencies</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br><br>import torch<br>import torchvision<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.utils.data import DataLoader<br>from torchvision.utils import make_grid<br>from torchvision import datasets, transforms</pre><p>2.Load the MNIST dataset, which is already available in torchvision</p><pre>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br># data transformations<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Normalize((0.5,), (0.5,))<br>])<br><br>#load the MNIST dataset<br>dataset = datasets.MNIST(root=&#39;data&#39;, train=True, transform=transform, download=True)<br><br># create dataLoader<br>batch_size = 64<br>num_workers = 2<br>dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)</pre><p>3. Plot train dataset.</p><pre># get a batch of images<br>actual_samples, _ = next(iter(dataloader))<br><br># create a grid of images from the batch<br>grid_imgs = torchvision.utils.make_grid(actual_samples, nrow=8, padding=2, normalize=True)<br><br># moving tensor from gpu to cpu and converting into numpy array<br>grid_imgs = np.transpose(grid_imgs.cpu().numpy(), (1, 2, 0))<br><br>plt.figure(figsize=(7, 7))<br>plt.title(&quot;MNIST Training Data Samples&quot;)<br>plt.imshow(grid_imgs, cmap=&#39;gray&#39;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><p>Above code plotted below figure that represents a sample from the dataset used to train the GAN model. It serves as the input for the model during the training phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*qHrRxDDRAgYvLptGHx2QWA.png" /></figure><p>4. Define parameters</p><pre>latent_dim = 100<br>batch_size = 64<br>lr = 0.0002<br>n_epochs = 150<br>sample_interval = 400</pre><p>5. Define generator</p><pre>class Generator(nn.Module):<br>    def __init__(self, latent_dim):<br>        super(Generator, self).__init__()<br>        self.model = nn.Sequential(<br>            nn.Linear(latent_dim, 128),<br>            nn.ReLU(True),<br>            nn.Linear(128, 256),<br>            nn.ReLU(True),<br>            nn.Linear(256, 512),<br>            nn.ReLU(True),<br>            nn.Linear(512, 1024),<br>            nn.ReLU(True),<br>            nn.Linear(1024, 1 * 28 * 28),<br>            nn.Tanh()<br>        )<br><br>    def forward(self, z):<br>        img = self.model(z)<br>        img = img.view(img.size(0), 1, 28, 28) # mnist dataset has images of size 28*28 and are in grayscale <br>        return img</pre><p>6. Define discriminator</p><pre>class Discriminator(nn.Module):<br>    def __init__(self):<br>        super(Discriminator, self).__init__()<br>        self.model = nn.Sequential(<br>            nn.Linear(1 * 28 * 28, 512),<br>            nn.LeakyReLU(0.2, inplace=True),<br>            nn.Linear(512, 256),<br>            nn.LeakyReLU(0.2, inplace=True),<br>            nn.Linear(256, 1),<br>            nn.Sigmoid()<br>        )<br><br>    def forward(self, img):<br>        img_flat = img.view(img.size(0), -1)<br>        discriminate = self.model(img_flat)<br>        return discriminate</pre><p>7. Model Initialization</p><pre>generator = Generator(latent_dim).to(device)<br>discriminator = Discriminator().to(device)</pre><p>8. Loss function</p><pre># Loss function to measures generator&#39;s ability to fool the discriminator<br>adversarial_loss = nn.BCELoss()<br># Optimizers<br>optimizer_G = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.999))<br>optimizer_D = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.999))</pre><p>8. Function to plot generated samples</p><pre>def plot_generated_images(generator, epoch):<br>    with torch.no_grad():<br>        z = torch.randn(25, latent_dim, device=device)<br>        gen_imgs = generator(z)<br>        gen_imgs = make_grid(gen_imgs.cpu(), nrow=5, normalize=True)<br>        plt.figure(figsize=(5,5))<br>        plt.imshow(np.transpose(gen_imgs.numpy(), (1, 2, 0)))<br>        plt.title(f&quot;Epoch {epoch}&quot;)<br>        plt.axis(&quot;off&quot;)<br>        plt.show()</pre><p>9. Training</p><pre>plot_interval = 10<br><br>for epoch in range(n_epochs):<br>    for i, (imgs, _) in enumerate(dataloader):<br><br>        # ground truths<br>        valid = torch.ones(imgs.size(0), 1, device=device, requires_grad=False)<br>        fake = torch.zeros(imgs.size(0), 1, device=device, requires_grad=False)<br><br>        real_imgs = imgs.to(device)<br>        optimizer_G.zero_grad()<br>        # noise as an input to generator network<br>        z = torch.randn(imgs.size(0), latent_dim, device=device)<br>        gen_imgs = generator(z)<br>        # generators loss to check it&#39;s ability to generate realistic samples <br>        g_loss = adversarial_loss(discriminator(gen_imgs), valid)<br><br>        g_loss.backward()<br>        optimizer_G.step()<br>        optimizer_D.zero_grad()<br><br>        # discriminators loss to meansure it&#39;s ability to classify real from generated one<br>        real_loss = adversarial_loss(discriminator(real_imgs), valid)<br>        fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake)<br>        d_loss = (real_loss + fake_loss) / 2<br><br>        d_loss.backward()<br>        optimizer_D.step()<br><br>        with torch.no_grad():<br>            real_preds = discriminator(real_imgs).detach().cpu().numpy()<br>            fake_preds = discriminator(gen_imgs.detach()).detach().cpu().numpy()<br>            real_acc = np.mean(real_preds&gt;0.5)<br>            fake_acc = np.mean(fake_preds&lt;0.5)<br>            d_acc = (real_acc + fake_acc)/2<br><br><br>    ## Plot generated images every 10 epochs<br>    if epoch % plot_interval == 0:<br>      plot_generated_images(generator, epoch)<br></pre><p>The above code is meant to illustrate how GANs work and may not produce the best results or realistic samples. As mentioned earlier in this article, training a GAN to achieve an equilibrium where both the generator and discriminator have minimal loss is quite challenging. You may need to experiment with different architectures for the generator and discriminator, as well as adjust parameters, to achieve optimal results.</p><p>References:</p><p><a href="https://arxiv.org/pdf/1406.2661">https://arxiv.org/pdf/1406.2661</a></p><p><a href="https://lilianweng.github.io/posts/2017-08-20-gan/">https://lilianweng.github.io/posts/2017-08-20-gan/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9784ec1a49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Inner Workings of Neural Networks: From Architecture to Back-propagation]]></title>
            <link>https://medium.com/@poudelsushmita878/the-inner-workings-of-neural-networks-from-architecture-activation-to-backpropagation-b60f8bb2cc61?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b60f8bb2cc61</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[weights-and-biases]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 16:52:01 GMT</pubDate>
            <atom:updated>2024-06-19T10:31:23.108Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural networks are a biologically-inspired programming paradigm that mimics the learning processes of the human brain, enabling computers to learn from data, recognize patterns, and generate insights. Just as a set of neurons in the biological nervous system work together to learn from experience and make decisions, interconnected layers of artificial neurons in neural networks collaborate to achieve similar outcomes. In this article we will delve into the core components of neural networks, the calculations that take place in each neuron, and the back-propagation algorithm, which allows the network to learn from data through training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*m_BErNAquMeo7uxfSbQz9Q.jpeg" /><figcaption>Fig 1: Biological Neurons Network <a href="https://neurosciencenews.com/artificial-brains-15709/">Img src</a></figcaption></figure><p>In biological nervous system, if a child sees cats and dogs for the first time, how will they be able to distinguish them? Typically, his mom or dad will explain the features of cats and dogs, helping the child recognize which pet is a cat and which one is a dog. The child learns that the pet with pointy ears, eyes of different colors, and a small body size is a cat, while the pet that is bigger in size and doesn’t have pointy ears is a dog. The child’s eyes take in these features, and the brain’s neurons process the information, enabling the child to distinguish the animals on their own. The next time child see the same pet, he can automatically recognize it from his past experience. Similarly, just as a human child learns about things and recognize object from experience, we can program neural networks with features, allowing them to recognize objects and perform a wide range of tasks automatically by learning from data, improving their performance through back-propagation during training.</p><p>Now let’s look into the detailed breakdown of what neural networks are and how they work.</p><h3>Neural Networks Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ub-ifcgdi9xgryqvo0_GRA.png" /><figcaption>Fig 2: Neural Network <a href="https://www.researchgate.net/profile/Facundo-Bre/publication/321259051/figure/fig1/AS:614329250496529@1523478915726/Artificial-neural-network-architecture-ANN-i-h-1-h-2-h-n-o.png">Img src</a></figcaption></figure><p>Neural Networks are formed of 3 key components: <strong>Input layer</strong>, <strong>hidden layers</strong>, and <strong>output layer</strong>. Each of these layers are made up of neurons that are fully connected to the neurons in the next layers. But not all kind of neural network’s neurons, such as CNN, are fully connected to neurons in the next layers. Neurons are the most basic units of a neural network that receive input, process it, and pass result to the neurons of the next layers. Each neurons has associated weight, bias, and an activation function, which we will see later in the article.</p><p><strong>Input Layer</strong> : The first layer in the neural network which receives initial data input.</p><p><strong>Hidden Layers</strong> : The middle layers of the neural network which is responsible for processing the input fed into the network from input layer, extracting meaningful features and patterns and generate insights. We can have one to many number of hidden layers in our network depending on the type of problem we aim our network to solve.</p><p><strong>Output Laye</strong>r : The last layer of the neural network that generates the output of the network, such as classification or prediction.</p><h3>How neural networks work?</h3><p>Neural networks operate in two main steps: forward propagation and backward propagation. Before diving into the details of these processes, let’s first understand the concept of weights and biases associated with each neuron in the network and computation in neurons.</p><p><strong>What are weights and biases? What is it’s role in neural networks?</strong></p><p>Weights and biases are fundamental parameters of neural networks used to model relationships between input data and output predictions.</p><ul><li>Weights are the parameters assigned to each input in the model, indicating the influence of that specific input features on generating the model’s predictions. They essentially capture the relationship between input features and the target output. A higher absolute value of a weight indicates a stronger connection and a greater influence of the corresponding input on the neuron’s output.</li><li>Bias is a constant value associated with each neuron that is not dependent on any input data. Unlike weights, which adjust the importance of input features, bias shifts the activation threshold of the neuron. By adding this constant value to the output, bias allows the neural network to learn more complex patterns and enhances the flexibility of the decision boundaries. This helps the network to make better predictions, even when the weighted sum of inputs is zero by improving the overall learning and performance of the model.</li></ul><p>The weighted sum of inputs refers to the multiplication of inputs with their associated weights,i.e, <strong>∑𝑥𝑖𝑤𝑖, </strong>as shown in the equation 1.</p><p><strong>Computation in neurons</strong> : The following figure illustrates the computation that occurs in each neuron of the neural network:</p><p><strong>𝑦 = 𝑓(∑𝑥𝑖𝑤𝑖+𝑏) — — — — — — — — — — — — — — — — — — — — — equation(1)</strong></p><p>where 𝑥𝑖​ are the inputs to the network, 𝑤𝑖 are the weights associated with each input, <em>b</em> is the bias term, and<strong> 𝑓 </strong>is an activation function which decides whether to activate neuron .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*YZSGApgEPn7JpntiDZAcQA.png" /><figcaption>Fig 3: Neuron Calculation . Image by Author</figcaption></figure><p><strong>What happens if we don’t add bias term?</strong><br>If we don’t add a bias term to a neural network, the linear function will always pass through the origin. This limitation means that the network may struggle to effectively model datasets where the classes are not naturally centered around the origin, particularly when the classes are not separable by a line passing through the origin. This will limit our models ability to learn complex patterns in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*soOhCaNG11OJp3DyfVcUHw.png" /><figcaption>Fig 4: Linear Function with and without bias. Image by Author</figcaption></figure><p><strong>Activation Functions</strong></p><p>Activation functions are the key components of neural network, serving as a non-linear decision making unit, which decided whether a neuron should be activated not, the output from the neuron will be propagated to the next layer neuron only if the neuron is activated, else wise the neuron would be dead means no information from it will be passed onto the next neuron. By introducing non-linearity, it enables model to understand and learn complex patterns within the data. Without activation function, neural networks are essentially a linear regression model. To better grasp the role of activation functions, refer to Figure 3 and Equation 1.</p><ol><li>Sigmoid Activation Function:<br>Sigmoid AF is a non-linear function, denoted as σ(x), and commonly known as the logistic function due to its S-shaped curve when plotted. It’s mathematical expression is:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*fqgHTIujGNh0qBFk-eeIDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBqMvDzRpuzypmf9bEGMow.png" /><figcaption>Fig 5: Sigmoid Activation Function and Its Derivative. Image by Author</figcaption></figure><ul><li>Sigmoid smoothly transits values between range from 0 to 1 as x varies from negative infinity to positive infinity.</li><li>Derivative of sigmoid function range from 0 to 0.25. As x moves away from 0 toward positive or negative infinity σ′(x) approaches 0, and as x approaches 0, σ′(x) approaches it’s maximum value 0.25.</li></ul><p>You might be curious about the explanation of derivatives here, but for now, let’s focus on understanding the concepts of these activation functions. In the neural network functioning section, we will explore the role of their derivatives during backpropagation.</p><ul><li>Use case: It is commonly used in the output layer of binary classification models as it produces output values between 0 and 1. Values greater than 0.5 indicate a predicted label of 1 (e.g., dog), while values less than or equal to 0.5 indicate a predicted label of 0 (e.g., cat).</li><li>Limitation: The main drawback of the sigmoid function is the <a href="https://medium.com/@amanatulla1606/vanishing-gradient-problem-in-deep-learning-understanding-intuition-and-solutions-da90ef4ecb54">vanishing gradient</a> problem, where the derivative becomes exceedingly small for large positive or negative values of its input, as shown in the graph above.</li></ul><p>2. Hyperbolic Tanh Activation Function:<br>The tanh activation function, denoted as tanh(x), is a non-linear function also known as the hyperbolic tangent function. Its mathematical expression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*Ce83Am7ygsTA1N0GcxZEaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JVuNZaiNx49F1zuh_ogBw.png" /><figcaption>Fig 6: Tanh Activation Function and Its Derivative. Image by Author</figcaption></figure><ul><li>The value for tanh function range from -1 to 1, as x varies from negative infinity to positive infinity it smoothly transits value from -1 to 1.</li><li>And the range of the derivative of the tanh function is [0,1]. As x moves away from 0 toward positive or negative infinity, the derivative of tanh, denoted as tanh’(x), approaches. Similarly, as x approaches 0, tanh’(x) approaches its maximum value of 1.</li><li>Use case: It is often preferred in <a href="https://medium.com/@poudelsushmita878/recurrent-neural-network-rnn-architecture-explained-1d69560541ef">Recurrent Neural Networks</a> due to its output range from -1 to 1. By using tanh in RNN, the network can accumulate both positive and negative signals over time without biasing gradients in one direction which helps in learning sequential dependency.</li><li>Limitation: Like Sigmoid, Tanh also has the problem of Vanishing gradient as the value of its input increases either in negative or positive axis, but to a slightly lesser extent.</li></ul><p>3. ReLU Activation Function:<br>In earlier functions, gradients of parameters could become exceedingly small, hindering the model’s ability to update weights effectively during training, which led to the problem of vanishing gradients. ReLU (Rectified Linear Unit) is a function specifically designed to address this issue. Mathematical expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*5RNrqnJy-jUWqr_HQym1Sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxZbc7OXqHr-SPwfsyf47w.png" /><figcaption>Fig 7: ReLU Activation Function and Its Derivative. Image by Author</figcaption></figure><ul><li>The value range of ReLU is [0,∞).<br>ReLU(x) = x, if x&gt;0<br>ReLU(x) = 0, if x≤0</li><li>Derivative of ReLU is either 0 or 1, depending on the value of x.<br>ReLU′(x) = 1, if x&gt;0<br>ReLU′(x) = 0, if x≤0</li><li>Since ReLU addresses the problem of vanishing gradients, it is the most preferred activation function for use in the internal layers of deep neural networks.</li><li>Limitation: Although ReLU overcomes the problem of vanishing gradients, it can lead to an issue called the “dying ReLU” problem. This occurs when the derivative is 0, causing neurons to become inactive and stop learning.</li></ul><p>4. Leaky ReLU: <br>Leaky ReLU is a variant of the standard ReLU activation function designed to mitigate the ‘dying ReLU’ problem. In standard ReLU, neurons can become inactive and cease learning when the input is less than or equal to zero because its derivative is zero in that region. To address this issue, Leaky ReLU introduces a small slope (often denoted as α\alphaα) for inputs less than or equal to zero. This small slope ensures that the gradient is not zero, allowing neurons to continue to learn even for negative inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwLWk0xfNYM9TTJstbNsKA.png" /><figcaption>Fig 8: Leaky ReLU Activation Function and Its Derivative. Image by Author</figcaption></figure><ul><li>It can be defined as,<br>Leaky ReLU(x)=x, if x&gt;0<br>Leaky ReLU(x) = αx, if x≤0<br>Here, α is a small constant, typically 0.01, which introduces a small slope for negative inputs.</li><li>The derivative of leaky ReLU is:<br>Leaky ReLU ′(x) = 1, if x&gt;0<br>Leaky ReLU ′(x) = 0.01, if x≤0</li></ul><p>5. Softmax Activation Function <br>Softmax is an activation function that is commonly used in the output layer of NN for multi-class classification. It converts logits into probabilities for multi-class classification. Given an input vector z, the softmax function for the i element is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*5B6Un2aKjRx7kYeWUkoP7A.png" /></figure><p>where, K is the total number of classes.</p><ul><li>It’s output range between 0 and 1.</li><li>If our neural network needs to classify four classes: cat, dog, rabbit, and squirrel, the output probabilities might be [0.259, 0.5, 0.142, 0.099].</li><li>The predicted label would be “dog” because it has the highest probability (0.5).</li></ul><p><strong>Functioning of Neural Network</strong></p><p><strong>Forward Propagation</strong> : In forward propagation, data are passed as an input to the network through the input layer. Each neuron processes its input, calculates the weighted sum, adds the bias, and applies the activation function to produces output. The output of neurons in first layer is then passed as an input to the next layer and the process is continued until the final out is produced by output layer.</p><p>Let’s assume, in the <strong>Fig 9 </strong>below, we’ve two input features, x₁ and x₂, are passed into the network through the input layer. These inputs are combined with their associated weights w₁₁⁽¹⁾, w₁₂⁽¹⁾, w₁₃⁽¹⁾, w₁₄⁽¹⁾, w₂₁⁽¹⁾, w₂₂⁽¹⁾, w₂₃⁽¹⁾, w₂₄⁽¹⁾ and passed to the neurons in the first hidden layer. The outputs from the neurons in the first hidden layer i.e o₁₁, o₁₂, o₁₃, o₁₄ then become inputs for the neurons in the second hidden layer, along with new weights w₁₁⁽²⁾, w₁₂⁽²⁾, w₁₃⁽²⁾, w₁₄⁽²⁾, w₂₁⁽²⁾, w₂₂⁽²⁾, w₂₃⁽²⁾, w₂₄⁽²⁾. Finally, the outputs from the second hidden layer o₂₁ and o₂₂ are combined with their weights w₁₁⁽³⁾ and w₂₁⁽³⁾ and passed to the final layer, which produces the network’s final output.</p><p><strong>Backward Propagation</strong> : Back propagation is a method used by neural networks to update the parameters — weights and biases — to minimize the error in prediction. The error is calculated by finding the difference between the actual and predicted values. An optimization algorithm, gradient descent, is used to minimize the loss. With gradient descent, the gradient of the loss function with respect to each weight and bias is computed. The network then adjusts the weights and biases using these gradients, reducing the error in subsequent iterations. This process is repeated over many epochs, with each epoch consisting of multiple iterations through the training data. Below mathematical operation can give better insight of this explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSEUOb59RmUkjsvqCj1TOA.png" /><figcaption>Fig 9: Forward and Backward propagation. Image by Author</figcaption></figure><p>The loss calculation and weight update rule for neural networks are as follows:</p><p>Loss (L) is calculated as the difference between the actual target value (y) and the predicted value (ŷ​).</p><p><strong>Loss (L) = y — ŷ</strong></p><p>To update the weights wₙₑ𝓌 associated with each layer, we subtract the gradient of the loss with respect to the old weights wₒₗ𝒹​ multiplied by a learning rate η.</p><p><strong>wₙₑ𝓌 = wₒₗ𝒹 − η * ∂L/∂wₒₗ𝒹</strong></p><p>Similarly, for the bias terms b, we update them using a similar procedure.</p><p><strong>bₙₑ𝓌 = bₒₗ𝒹 − η * ∂L/∂bₒₗ𝒹</strong></p><p>Let’s explore the weight update process throughout the neural network by focusing on three specific weights linked to the initial neurons of different layers: w₁₁⁽¹⁾, w₁₁⁽²⁾ and w₁₁⁽³⁾.</p><ul><li>Updating the weight w₁₁⁽³⁾ as,<br><strong>w₁₁⁽³⁾ₙ = w₁₁⁽³⁾ₒ — η * ∂L/∂w₁₁⁽³⁾ₒ</strong></li></ul><p>The loss function L depends on the output of the last layer neuron o₃₁, which in turn depends on the weights w₁₁⁽³⁾ connecting the last hidden layer to the output layer. By applying the chain rule of derivative,</p><p><strong>∂L/∂w₁₁⁽³⁾ₒ = ∂L/∂o₃₁ * ∂o₃₁/∂w₁₁⁽³⁾</strong></p><ul><li>Updating the weight w₁₁⁽²⁾ as,<br><strong>w₁₁⁽²⁾ₙ = w₁₁⁽²⁾ — η * ∂L/∂w₁₁⁽²⁾ₒ</strong></li></ul><p>The loss function L depends on the output of the last layer neuron o₃₁, which in turn depends on the output of the second layer neuron o₂₁, which is influenced by the weight w₁₁⁽²⁾. By applying the chain rule of derivatives, we can decompose the gradient of L with respect to w₁₁⁽²⁾ as follows</p><p><strong>∂L/∂w₁₁⁽²⁾ₒ = [∂L/∂o₃₁ * ∂o₃₁/∂o₂₁ * ∂o₂₁/∂w₁₁⁽²⁾]</strong></p><ul><li>Updating the weight w₁₁⁽¹⁾ as,<br><strong>w₁₁⁽¹⁾ₙ = w₁₁⁽¹⁾ — η * ∂L/∂w₁₁⁽¹⁾ₒ</strong></li></ul><p>The loss function L depends on the output of the last layer neuron o₃₁, which, in turn, relies on the output of the second hidden layer neuron o₂₁. The output o₂₁ is influenced by the output of first hidden layer’s neuron o₁₁⁽²⁾, driven by the weight, w₁₁⁽¹⁾. Additionally, there is also another part which is influenced by the same weight, w₁₁⁽¹⁾, leading from w₁₁⁽¹⁾ to o₁₁, o₂₂, o₃₁ and eventually to the loss. Therefore, to ensure both pathways are considered during weight w₁₁⁽¹⁾ updates, we must incorporate the gradient contributions from this second pathway as well. In simpler term this means, changes in w₁₁⁽¹⁾ impacts o₁₁, o₂₁, o₂₂, and o₃₁. So, by applying the chain rule of derivatives to both pathways, we obtain:</p><p><strong>∂L/∂w₁₁⁽¹⁾ₒ = [∂L/∂o₃₁ * ∂o₃₁/∂o₂₁ * ∂o₂₁/∂o₁₁ * ∂o₁₁/w₁₁⁽¹⁾] + [∂L/∂o₃₁ * ∂o₃₁/∂o₂₂ * ∂o₂₂/∂o₁₁ * ∂o₁₁/w₁₁⁽¹⁾]</strong></p><p>In similar way, biases as well are updated and the network fine-tunes its connections between neurons by updating all other weights as well. This continual weighs adjustment process plays a crucial role in minimizing errors and boosting the network’s performance over time.</p><p>Having discussed about the adjustment of weights and biases in the network, it is evident that these adjustments play a vital role in refining the network’s performance. However, there is another essential factor that you too may have noticed above that significantly influence the networks ability to learn complex patterns, i.e. activation function, we already discussed above.</p><p>Throughout this article, we explored the detailed aspects of neural networks, from their foundational components to their operational mechanisms. By understanding these components and processes, I hope you’ve gained insights into how neural networks can model complex data relationships, predict outcome and solve problems across diverse domains.</p><p>As technology continue to advance, neural networks will undoubtedly play a vital role in shaping the future of AI and driving innovations across industries. Thank you for joining me in this article. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b60f8bb2cc61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Classification Metrics: Precision, Recall, and More — Simplified Guide]]></title>
            <link>https://medium.com/@poudelsushmita878/understanding-classification-metrics-precision-recall-and-more-simplified-guide-ce927d8358d8?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce927d8358d8</guid>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[roc-curve]]></category>
            <category><![CDATA[classification-report]]></category>
            <category><![CDATA[precision]]></category>
            <category><![CDATA[recall]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Sat, 11 May 2024 16:08:10 GMT</pubDate>
            <atom:updated>2024-05-13T08:45:28.285Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of machine learning, the journey doesn’t end with model development. Even after parameter tuning, determining the effectiveness of our model and selecting the best parameters remains crucial. How can we ensure our model is effectively learning the features needed to distinguish between target classes? This is where evaluation metrics comes into play, providing valuable insights into our model’s performance and generalization ability.</p><p>Depending on the problem we aim to solve, whether it’s regression or classification, there exists a variety of metrics to estimate a model’s performance. The<a href="https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics"><strong>sklearn.metrics</strong></a> module of scikit-learn provieds functions for assessing and evaluating model’s performance across various ML tasks. In this article, we will delve specifically into the classification metrics, beginning with those found in scikit-learn’s classification_report and auc_roc_score .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*TjGx0o_C-oPPQ0tbkGuj2g.png" /><figcaption>fig 1: Binary classification scatter plot</figcaption></figure><p>While accuracy is the most commonly metric to evaluate a machine learning classification model, it doesn’t always provide a comprehensive understanding of the model’s discrimination ability across all classes and scenarios. Though it indicate whether our model makes correct predictions overall, it falls short in revealing class-specific performance, especially when there is class imbalance in the dataset. This is where metrics like precision and recall come into play. Let’s assuming 0 to be -ve class and 1 to be +ve class, in below classifcation report.</p><pre>from sklearn.metrics import classification_report<br># returns class-wise precision, recall, f1-score, support, accuracy, macro average, weighted average<br>classification_report(y_true, y_pred)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*qXRHCYC-ibGMwWO5kPp0AQ.png" /><figcaption>fig: Classification Report Heatmap</figcaption></figure><p><strong>Accuracy</strong>: Accuracy measures the proportion of correctly predicted labels in comparison to the actual labels in the test set. For instance, considering the values of y_true versus y_pred as depicted in the table below, we can compute accuracy using the formula (TP + TN) / (TP + TN + FP + FN), resulting in an accuracy of 0.9, indicating that 90% of our model&#39;s predictions are accurate.</p><ul><li>True Positives (TP): 2(2 “+ve” instances predicted correctly)</li><li>True Negatives (TN): 7(7 “-ve” instances predicted correctly)</li><li>False Positives (FP): 0(0 “-ve” instance incorrectly predicted as “+ve”)</li><li>False Negatives (FN): 1(1 “+ve” instances incorrectly predicted as “-ve”)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*6XC0oVjSvlAsRQvaCnZSyg.png" /><figcaption>Table 1: y_true vs y_pred</figcaption></figure><p><strong>Precision</strong>: Precision quantifies the accuracy of positive prediction made by the model. In situations where minimizing false positives is a deal, precision serves as a crucial metric. It is calculated separately for both positive and negative classes.</p><p>For positive class: It measures of all the instances predicted as positive how many are actually positive.A higher precision score indicated fewer false positives, calculated as TP/(TP+FP). From above table, for +ve class, since our model has made no false positive prediction (FP=0), the precision score is calculated to be 1, calculated as 2/(2+0) , indicating that there are no negative instances predicted as positive.</p><p>For negative class: To calculate the precision score for the negative class, we need to treat the negative class as positive and the positive class as negative which will allows us to evaluate the accuracy of negative predicition. The precision for the negative class is also calculated as TP / (TP + FP), as we treat the negative class as positive, now TP is the number of true negatives and FP is the number of false positives.In short, for negative class, the precision score is determined by the number of true negatives and false negatives. Therefore, it will be calculated as 7 / (7 + 1) = 0.875.</p><p><strong>Recall</strong>: Recall measures the ability of model to capture all positive instance son the dataset. In critical scenarios such as COVID-19 classification, where not a single positive instance should be misclassified as negative, recall becomes a major metrics to prioritize. A higher recall score indicates that the model is making lesser false negative prediction. Recall score of 1 suggests that our model don’t miss even a single +ve instance to classify as positive</p><p>For positive class: Recall is calculated as TP / (TP + FN). In the provided table, there is one false negative prediction for the positive class, so the recall will 2 / (2 + 1) = 0.666.</p><p>For the negative class: Similar to precision, we treat the negative class as positive and vice versa. Therefore, there are 0 false negative predictions for the negative class because none of the negative instances are classified as positive. As a result, the recall with 0 false negatives and 7 true positives will be calculated as 7 / (7 + 0) = 1.</p><p><strong>F1-score</strong>: F1-score provide the harmonic mean of precision and recall. It’s calculation is equally influenced by both precision and recall calculated as 2*precision*recall/(precision+recall). It can be used in scenarios where both the precision and recall are equally important, such as, fraud detection, where accurately identifying fraudulent activities while minimizing false alarms is vital. Additionally, as it provides harmonic mean of precision and recall, it’s useful for evaluating models in the presence of class imbalance, as seen in our above table, where there are 7 instances of negative samples and only 3 instances of positive samples.</p><p>In the provided data, the f1-score for the positive class is calculated as 2 * precision * recall / (precision + recall), resulting in a value of 0.79. Likewise, for the negative class, the f1-score yields 0.92.</p><p><strong>Support</strong>: Support represents the total number of samples available for each class. In our case, the support for the positive class is 3 because there are only 3 instances for that class, while for the negative class, it is 7.</p><p><strong>Macro average</strong>: Macro average calculates the average of metrics across all classes. For instance, macro average precision is calculated as (precision_for_pos_class + precision_for_neg_class)/no. of classes, in our case, it is: (1+0.875)/2 = 0.937. Macro average recall and macro average f1-score is also calculated in the same way.</p><p><strong>Weighted average</strong>: Weighted average takes into account the class imbalance by weighting the contribution of each class’s metric (e.g., precision, recall, F1-score) by the support (number of instances) of that class. It computes the average by multiplying each class’s score by its support and then calculating the weighted sum. For example, weighted average precision is calculated as (precision_for_pos_class * support + precision_for_neg_class * support) / (support_for_pos_class + support_for_neg_class), resulting in (1 * 7 + 0.875 * 3) / (3 + 7) = 0.91 in our case. Weighted average recall and F1-score follow the same approach.</p><p><strong>Roc-auc score</strong>: ROC AUC score measures the area under curve, which is a plot of the true positive rate (sensitivity) against the false positive rate (specificity) at various threshold levels, calculated as,</p><p>TPR = TP/(TP+FP); FPR = FP/(FP/TN)</p><p>The threshold level refers to the cutoff point used to convert predicted probabilities into binary prediction. For example, in a binary classification problem, if the predicted probability of the positive class is greater than the threshold, the instance is classified as positive, otherwise, it is classified as negative. The predicted probabilities for both classes (positive and negative) are obtained using the predict_proba() method in scikit-learn, which returns probabilities for each class.</p><p>A ROC AUC score of 0.5 suggests that the model is randomly guessing the target, while a score of 1 indicates perfect discrimination ability. The closer the ROC AUC score is to 1, the better the discrimination ability of the model.</p><p>To compute the ROC AUC score, we need two parameters: y_test, containing the true labels, and y_predicted_probability, containing the predicted probabilities for the positive class. With those, TPR and FPR are then calculated at various threshold values. For example: let’s calculate the tpr and fpr at threshold levels (0, 0.3, 0.7, 1) from the y_true, y_predicted_probab and y_pred label given at various threshold level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*n3Wq7J6pLrQnBgaCbD0Vow.png" /><figcaption>Table 2: y_true vs y_pred (at various threshold level)</figcaption></figure><p>Obtained,</p><p>At threshold 0, TPR=1, FPR=1<br>At threshold 0.3, TPR=0.33, FPR=0.14<br>At threshold 0.7, TPR=0, FPR=0.42<br>At threshold 1, TPR=0, FPR=0</p><p>After having TPR and FPR at various threshold levels it is plotted to generate ROC curve(Plot below is not obtained by plotting the above result, it is taken somewhere from the internet just for a sample). Each point on the curve represents the TPR and FPR obtained at a specific threshold level. Eventually connecting these points from TPR and FPR forms a roc curve. The larger the area below the curve the better the model. In the plot below, the pink colored curve represents the ideal scenario with a ROC score of 1-indicating the best classifier, while the red-dotted line represents a model that performs no better than random guessing, with a ROC score of 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmamA2_evp504Iz6P2E1jg.png" /><figcaption>Fig: roc-auc curve (<a href="https://stats.stackexchange.com/questions/523760/regarding-roc-curve-of-good-classifier-why-tpr-and-fpr-both-increase">Img src</a>)</figcaption></figure><p>With scikit-learn it can be calculated as,</p><pre>from sklearn.metrics import roc_auc_score, roc_curve<br><br># roc_curvve returns tpr, fpr and corresponding threshold value att which the curve was evaluated<br># y_predicted_probab can be obtained as model.predict_proba(X_test) it will return an array of probability for each class, we will have to pass the probability of a particular class as a prediccted probab to roc_curve<br>tpr, fpr, threshold = roc_curve(y_true, y_predicted_probab)<br># roc_auc_score returns a single output representing the area under the curve, the higher the value, the better the model can discriminate<br>roc_auc_score(y_true, y_predicted_probab)</pre><p>In this article, we covered metrics used to evaluate machine learning models and their use cases. All the metrics we explored and discussed above (accuracy, precision, recall, macro average, weighted average, F1-score, AUC-ROC score, ROC curve) can be applied to any type of classification problem. However, the ROC curve is primarily designed for binary classification tasks. Nevertheless, it can be adapted for multiclass classification by considering each class separately using a one-vs-all or one-vs-one approach.</p><p>Lastly, as you continue your journey in machine learning, remember to experiment with different evaluation techniques, explore advanced metrics for better understanding your model’s ability.</p><p>Thank you for reading the article. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce927d8358d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurrent Neural Network (RNN) Architecture Explained]]></title>
            <link>https://medium.com/@poudelsushmita878/recurrent-neural-network-rnn-architecture-explained-1d69560541ef?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d69560541ef</guid>
            <category><![CDATA[rnn-architecture]]></category>
            <category><![CDATA[bptt]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 04:52:49 GMT</pubDate>
            <atom:updated>2023-08-28T05:02:33.914Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will provide insights into RNNs and the concept of backpropagation through time in RNN, as well as delve into the problem of vanishing and exploding gradient descent in RNNs.</p><p>Recurrent Neural Networks (RNNs) were introduced to address the limitations of traditional neural networks, such as FeedForward Neural Networks (FNNs), when it comes to processing sequential data. FNN takes inputs and process each input independently through a number of hidden layers without considering the order and context of other inputs. Due to which it is unable to handle sequential data effectively and capture the dependencies between inputs. As a result, FNNs are not well-suited for sequential processing tasks such as, language modeling, machine translation, speech recognition, time series analysis, and many other applications that requires sequential processing. To address the limitations posed by traditional neural networks, RNN comes into the picture.</p><p>RNN overcome these limitations by introducing a recurrent connection that allow information to flow from one time-step to the next. This recurrent connection enables RNNs to maintain internal memory, where the output of each step is fed back as an input to the next step, allowing the network to capture the information from previous steps and utilize it in the current step, enabling model to learn temporal dependencies and handle input of variable length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*0x9dGTEEQCBGku3cT5nCug.png" /><figcaption>fig 1: FeedForward Neural Network (FNN). Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*RbFBiWhUqBkb-imi-tp5pg.png" /><figcaption>fig 2: Recurrent Neural Network (RNN). Image by Author</figcaption></figure><h4>Architecture Of RNN</h4><p>For more clear understanding of the concept of RNN, let’s look at the unfolded RNN diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*dznTsiaHCvRc70fxWWEcgw.png" /><figcaption>fig 3: RNN Unfolded. Image by Author.</figcaption></figure><p>The RNN takes an input vector <strong>X</strong> and the network generates an output vector <strong>y</strong> by scanning the data sequentially from left to right, with each time step updating the hidden state and producing an output.<strong> </strong>It shares the same parameters across all time steps. This means that, the same set of parameters, represented by U, V, W is used consistently throughout the network. U represents the weight parameter governing the connection from input layer <strong>X</strong> to the hidden layer <strong>h</strong> , W represents the weight associated with the connection between hidden layers, and V for the connection from hidden layer <strong>h</strong> to output layer <strong>y</strong>. This sharing of parameters allows the RNN to effectively capture temporal dependencies and process sequential data more efficiently by retaining the information from previous input in its current hidden state.</p><p>At each time step t, the hidden state aₜ is computed based on the current input xₜ , previous hidden state aₜ₋₁ and model parameters as illustrated by the following formula:</p><p>aₜ = f(aₜ₋₁, xₜ; θ) — — — — — (1)</p><p>It can also be written as,</p><p>aₜ = f(U * Xₜ + W* aₜ₋₁ + b)<br>where,</p><ul><li>aₜ represents the output generated from the hidden layer at time step t .</li><li>xₜ is the input at time step t.</li><li>θ represents a set of learnable parameters(weights and biases).</li><li>U is the weight matrix governing the connections from the input to the hidden layer; U ∈ θ</li><li>W is the weight matrix governing the connections from the hidden layer to itself (recurrent connections); W∈ θ</li><li>V represents the weight associated with connection between hidden layer and output layer; V∈ θ</li><li>aₜ₋₁ is the output from hidden layer at time t-1.</li><li>b is the bias vector for the hidden layer; b ∈ θ</li><li>f is the activation function.</li></ul><p>For a finite number of time steps T=4, we can expand the computation graph of a Recurrent Neural Network, illustrated in Figure 3, by applying the equation (1) T-1 times.</p><p>a₄ = f(a₃, x₄; θ) — — — — — (2)</p><p>Equation (2) can be expanded as,</p><p>a₄ = f(U * X₄ + W* a₃ + b)</p><p>a₃ = f(U * X₃ + W* a₂ + b)</p><p>a₂ = f(U * X₂ + W* a₁ + b)</p><p>The output at each time step t, denoted as yₜ is computed based on the hidden state output aₜ using the following formula,</p><p>ŷₜ = f(aₜ; θ) — — — — — (3)</p><p>Equation (3) can be written as,</p><p>ŷₜ = f(V * aₜ + c)</p><p>when t=4, ŷ₄ = f(V * a₄ + c)</p><p>where,</p><ul><li>ŷₜ is the output predicted at time step t.</li><li>V is the weight matrix governing the connections from the hidden layer to the output layer.</li><li>c is the bias vector for the output layer.</li></ul><h4>Backpropagation Through Time (BPTT)</h4><p>Backpropagation involves adjusting the model’s parameters (weights and biases) based on the error between predicted output and the actual target value. The goal of backpropagation is to improve the model’s performance by minimize the loss function. Backpropagation Through Time is a special variant of backpropagation used to train RNNs, where the error is propagated backward through time until the initial time step t=1. Backpropagation involves two key steps: forward pass and backward pass.</p><ol><li><strong>Forward Pass</strong>: During forward pass, the RNN processes the input sequence through time, from t=1 to t=n, where n is the length of input sequence. In each forward propagation, the following calculation takes place</li></ol><blockquote>aₜ = U * Xₜ + W* aₜ₋₁ + b<br>aₜ = tanh(aₜ)<br>ŷₜ = softmax(V * aₜ + c)</blockquote><p>After processing the entire sequence, RNN generates a sequence of predicted outputs<em> ŷ =[ŷ₁, ŷ₂, …, ŷₜ]</em>. Loss is then computed by comparing predicted output ŷ at each time step with actual target output y. Loss function given by,</p><blockquote>L(y, ŷ) = (1/t) * Σ(yₜ — ŷₜ)² — — —— — -&gt; MSE Loss</blockquote><p><strong>2. Backward Pass:</strong> The backward pass in BPTT involves computing the gradients of the loss function with respect to the network’s parameters (U, W, V and biases) over each time step.</p><p>Let’s explore the concept of backpropagation through time by computing the gradients of loss at time step t=4. The figure below also serves as an illustration of backpropagation for time step 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*GY4IdPt5EF7mfsBXcjXPpg.png" /><figcaption>fig 4: Back Propagation Through Time (BPTT). Image by Author</figcaption></figure><p><strong>Derivative of loss L w.r.t V</strong></p><p>Loss L is a function of predicted value ŷ, so using the chain rule ∂L/∂V can be written as,</p><p>∂L/∂V = (∂L/∂ŷ) * (∂ŷ/∂V)</p><p><strong>Derivative of loss L w.r.t W</strong></p><p>Applying the chain rule of derivatives ∂L/∂W can be written as follows: The loss at the 4th time step is dependent upon ŷ due to the fact that the loss is calculated as a function of ŷ, which is in turn dependent on the current time step’s hidden state a₄, a₄ is influenced by both Wand a₃, and again a₃is connected to both a₂and W,and a₂ depends on a₁and also on W.</p><p>∂L₄/∂W = (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ * ∂a₄/∂W) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃*∂a₃/∂W) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃*∂a₃/∂a₂*∂a₂/∂W) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃* ∂a₃/∂a₂*∂a₂/∂a₁*∂a₁/∂W)</p><p><strong>Derivative of loss L w.r.t U</strong></p><p>Similarly, ∂L/∂U can be written as,</p><p>∂L₄/∂U = (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ * ∂a₄/∂U) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃*∂a₃/∂U) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃*∂a₃/∂a₂*∂a₂/∂U) + (∂L₄/∂ŷ₄ * ∂ŷ₄/∂a₄ *∂a₄/∂a₃*∂a₃/∂a₂*∂a₂/∂a₁*∂a₁/∂U)</p><p>Here we’re summing up the gradients of loss across all time steps which represents the key difference between BPTT and regular backpropagation approach.</p><h4><strong>Limitations of RNN</strong></h4><p>During backpropagation, gradients can become too small, leading to the vanishing gradient problem, or too large, resulting in the exploding gradient problem as they propagate backward through time. In the case of vanishing gradients, the issue is that the gradient may become too small where the network struggles to capture long-term dependencies effectively. It can still converge during training but it may take a very very long time. In contrast, in exploding gradient problem, large gradient can lead to numerical instability during training, causing the model to deviate from the optimal solution and making it difficult for the network to converge to global minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*DMVXP_4LS68SS35bqk3wcQ.png" /><figcaption>fig 5: Gradient Descent. <a href="https://srdas.github.io/DLBook/GradientDescentTechniques.html">Image Source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*heQR61fa32f8OzjYSyE5tg.png" /><figcaption>fig 6: Vanishing and Exploding Gradient. <a href="https://srdas.github.io/DLBook/GradientDescentTechniques.html">Image Source</a></figcaption></figure><p>To address these problems, variations of RNN like Long-short term memory (LSTM) and Gated Recurrent Unit (GRU) networks have been introduced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d69560541ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross Validation in Time Series Forecasting]]></title>
            <link>https://medium.com/@poudelsushmita878/cross-validation-in-time-series-forecasting-db2bc7601875?source=rss-8ef7cf8b0ce7------2</link>
            <guid isPermaLink="false">https://medium.com/p/db2bc7601875</guid>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sushmita Poudel]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 13:13:44 GMT</pubDate>
            <atom:updated>2023-10-10T15:32:56.252Z</atom:updated>
            <content:encoded><![CDATA[<p>Cross-validation is a statistical method used to evaluate the performance of machine learning models. It involves dividing a dataset into multiple sets or folds, and iteratively using each fold as a test set while training the model on the remaining folds. The purpose of cross validation is to provide an accurate estimate of the model’s ability to generalize to new, unseen data.</p><p>The most common form of cross-validation is <strong>k-fold cross-validation</strong> where the data is randomly shuffled and is partitioned into k folds of approximately the same size. The model is then trained on k-1 folds and evaluated on the remaining folds. This process repeats k times, with each fold serving as a validation set once. The result of each fold is then averaged to get an estimate of the model’s overall performance.</p><p>But the traditional cross-validation approach is not suitable for use in analyzing time series data.</p><p><strong>Why traditional cross validation methods like K-fold cannot be used in time-series?</strong></p><p>In a time series dataset, the observations are ordered by timely manner, and each observation is dependent on the previous observations. The data is not independently and identically distributed in time-series. Unlike traditional cross-validation methods where data is randomly shuffled and splitted, <strong>time series cross-validation</strong> requires maintaining the order of the data, ensuring that the model is evaluated on data that comes after the data used for training. So to apply the concept of cross-validation to time series data, we need to use methods that takes into account the temporal aspect of the data.</p><p>scikit-learn has provided us a class TimeSeriesSplit that implements time series cross-validation. It is a variation of k-fold cross validation, specially designed for time-series data. The beauty of TimeSeriesSplit cross-validation is that it splits the data into specified number of folds by preserving the chronological order of the observations. Simply speaking, it preserves the temporal dependency of the data, which is not possible by other cross-validation techniques.</p><p>The TimeSeriesSplit class can be imported from the model_selection module of the scikit-learn library which takes the number of splits, n_splits, as an input. Optionally, it also takes parameters:</p><p>max_train_size : specifies the maximum number of data points that can be in the train set of each fold/split.</p><p>test_size : specifies the size of the test or validation set.</p><p>gap: represents the number of time units to exclude between the end of the training set and the start of the validation set for each split. With this you can avoid data leakage and ensure that the model is evaluated on unseen data. For example, let’s say you have a time series data with daily time intervals and you are using TimeSeriesSplit with n_splits=5, test_size=0.2, and gap=2. In this case, the data will be splitted into 5 folds, and the testing set for each fold will contain 20% of the data (the most recent data) with a gap of 2 days between the end of the training set and the start of the testing set. This means that the first testing set will start 2 days after the end of the first training set, the second testing set will start 2 days after the end of the second training set, and so on.</p><p>You can learn more about TimeSeriesSplit by referring to its <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html">documentation</a> .</p><p>Let’s take a concrete example to better grasp the concept of cross-validation in time-series.</p><p>Suppose we have a dataset that consists of a sequence of data points over time, and we choose to perform cross-validation with 5 folds. In this case, the time series data will be splitted into 5 different folds, and the model will undergo training and evaluation 5 times, with each time using a distinct block for model evaluation. In first iteration, the model will be trained on the first block and its performance be evaluated on the second block. Similarly, in second iteration, the first two block of the data will be used for training and the third block be used as a validation set. The process will be carried out five times, with each iteration utilizing a distinct block, which comes after the training set, as a validation set.</p><p>In order to gain a deeper comprehension of the concept discussed above, examine the following illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*C3ZF0rTsu23174cv_i1_2w.png" /><figcaption>fig:5-fold cross-validation in time series. Image by Author</figcaption></figure><p>TimeSeriesSplit with Gap between training and validation set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*293W3A2gWHsMsW1aO0A6ng.png" /><figcaption>fig: 5-fold cross-validation with a gap between train set and validation set. Image by Author</figcaption></figure><p><strong>Implementation</strong></p><p>Now, let’s go through it’s implementation. Here, we have to forecast the temperature of a particular city by using the parameters: humidity, wind_speed, mean_pressure .</p><ol><li>Import the necessary modules</li></ol><pre>import pandas as pd<br>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_absolute_error</pre><p>2. Read data and assign X and y variables</p><pre>df = pd.read_csv(&#39;temperature.csv&#39;)<br>X = df[[&#39;humidity&#39;, &#39;wind_speed&#39;, &#39;mean_pressure&#39;]]<br>y = df[&#39;Temp&#39;]</pre><p>3. Train-test split.</p><pre>train_X, train_y = X.iloc[:-1200], y.iloc[:-1200] <br>test_X, test_y = X.iloc[-1200:], y.iloc[-1200:]</pre><p>3. Split the data into train and test set using TimeSeriesSplit function.</p><pre># 5-fold cross validation<br>tscv = TimeSeriesSplit(n_splits=5, test_size=1200)<br>for fold, (train_index, test_index) in enumerate(tscv.split(train_X)):<br>  X_train, X_test = train_X.iloc[train_index, :], train_X.iloc[test_index,:]<br>  y_train, y_test = train_y.iloc[train_index], train_y.iloc[test_index]<br>  print(&quot;Fold: {}&quot;.format(fold))<br>  print(&quot;\tTRAIN indices:&quot;, train_index)<br>  print(&quot;\tTEST indices:&quot;, test_index)</pre><p>Output:</p><pre>Fold: 0<br> TRAIN indices: [   0    1    2 ... 2130 2131 2132]<br> TEST indices: [2133 2134 2135 ... 3330 3331 3332]<br>Fold: 1<br> TRAIN indices: [   0    1    2 ... 3330 3331 3332]<br> TEST indices: [3333 3334 3335 ... 4530 4531 4532]<br>Fold: 2<br> TRAIN indices: [   0    1    2 ... 4530 4531 4532]<br> TEST indices: [4533 4534 4535 ... 5730 5731 5732]<br>Fold: 3<br> TRAIN indices: [   0    1    2 ... 5730 5731 5732]<br> TEST indices: [5733 5734 5735 ... 6930 6931 6932]<br>Fold: 4<br> TRAIN indices: [   0    1    2 ... 6930 6931 6932]<br> TEST indices: [6933 6934 6935 ... 8130 8131 8132]</pre><p>Here, we see in first fold the index of train set range from 0 to 2132 and the test set range from 2133 to 3332. And for the second fold, the training set index spans from 0 to 3332, indicating that the index previously used as the test set in the first fold is now employed as the training set.</p><p>4. Train and evaluate the model forecasting</p><pre>avg_mae = []<br>for fold, (train_index, test_index) in enumerate(tscv.split(train_X)):<br>  X_train, X_test = train_X.iloc[train_index, :], train_X.iloc[test_index,:]<br>  y_train, y_test = train_y.iloc[train_index], train_y.iloc[test_index]<br>  pipeline_lr = Pipeline(steps = [(&#39;scaler&#39;, StandardScaler()),<br>                               (&#39;lr&#39;, LinearRegression())])<br>  pipeline_lr.fit(X_train, y_train)<br>  y_pred = pipeline_lr.predict(X_test)<br>  mae = mean_absolute_error(y_test, y_pred)<br>  avg_mae.append(mae)<br>  print(&quot;Fold: {}&quot;.format(fold))<br>  print(&#39;\tMAE on test set: %.3f&#39; %mae)<br>print(&#39;\nAverage MAE: %.3f%%&#39; %np.array(avg_mae).mean())</pre><p>Output:</p><pre>Fold: 0<br> MAE on test set: 2.404<br>Fold: 1<br> MAE on test set: 1.834<br>Fold: 2<br> MAE on test set: 1.777<br>Fold: 3<br> MAE on test set: 2.527<br>Fold: 4<br> MAE on test set: 1.976<br>Average MAE: 2.104</pre><p>Conclusion:</p><p>This article explored the concept of cross-validation in time series analysis and highlighted the limitations of using traditional cross-validation techniques for time-series data. Additionally, it discussed the approach to implement cross-validation for time-series data using the scikit-learn library.</p><p>References:</p><ul><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html">TimeSeriesSplit</a></li><li><a href="https://towardsdatascience.com/4-things-to-do-when-applying-cross-validation-with-time-series-c6a5674ebf3a">4 Things to Do When Applying Cross-Validation with Time Series</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db2bc7601875" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>