<?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 Koushik Ahmed Kushal on Medium]]></title>
        <description><![CDATA[Stories by Koushik Ahmed Kushal on Medium]]></description>
        <link>https://medium.com/@koushikkushal95?source=rss-1670d68f972f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SIURKlXK6uuWRyOAeGfKhw.png</url>
            <title>Stories by Koushik Ahmed Kushal on Medium</title>
            <link>https://medium.com/@koushikkushal95?source=rss-1670d68f972f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:42:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@koushikkushal95/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[How Retrieval-Augmented Generation Enhances AI Responses]]></title>
            <link>https://medium.com/@koushikkushal95/understanding-retrieval-augmented-generation-rag-b5aa0279af74?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5aa0279af74</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 18:58:43 GMT</pubDate>
            <atom:updated>2026-01-24T10:41:47.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Y8VMhxFjY_EMYE0ARqAVw.jpeg" /><figcaption>RAG Diagram</figcaption></figure><p>Hey there! If you’re dipping your toes into the world of AI and machine learning, you’ve probably heard buzzwords like “large language models” (LLMs) thrown around. But today, I want to chat about something super practical and game-changing: Retrieval-Augmented Generation, or RAG for short. Imagine you’re trying to answer a tricky question, not just from what you remember, but by quickly grabbing the right book from your shelf and flipping to the perfect page. That’s RAG in a nutshell. It’s a way to make AI smarter by combining real-time information retrieval with creative generation.</p><p>In this post, I’ll break it down step by step, like we’re having a coffee chat. No heavy jargon, I’ll explain everything as we go. By the end, you’ll get why RAG is blowing up in applications like chatbots, search engines, and even content creation. Plus, I’ll sprinkle in some visuals to make it clearer. Let’s dive in!</p><h3>What Is RAG, Anyway?</h3><p>Picture this: Traditional AI models, like ChatGPT or Grok, are trained on massive amounts of data. They “remember” patterns from that training and spit out responses based on probabilities. But here’s the catch — they can hallucinate (make stuff up) or get outdated because their knowledge is frozen in time.</p><p>RAG fixes that by adding a “retrieval” step. It’s like giving the AI a super-fast library card. When you ask a question, the system first searches a database or knowledge base for relevant info, pulls out the good stuff, and then uses that to craft a more accurate, grounded response. The “augmented” part means it blends this retrieved info with the model’s generative powers.</p><p>Why does this matter? In a world where info changes daily (think stock prices, news, or tech updates), RAG keeps things fresh without retraining the entire model, which is expensive and time-consuming.</p><h3>How Does RAG Work? A Step-by-Step Breakdown</h3><p>Alright, let’s get into the nuts and bolts. I’ll explain it like I’m teaching a friend who’s new to this. RAG typically involves three main phases: Retrieval, Augmentation, and Generation. Here’s how it flows:</p><ol><li><strong>The Query Comes In</strong>: You ask something, say, “What’s the latest on quantum computing breakthroughs?” The system takes your question as input.</li><li><strong>Retrieval: Hunting for Relevant Info</strong>: This is where the magic starts. The AI doesn’t just wing it, it searches a vector database (think of it as a smart index where info is stored as mathematical vectors for quick similarity matching). It uses embeddings (fancy word for turning text into numbers) to find chunks of text that match your query. Tools like Pinecone or FAISS handle this behind the scenes.</li><li>For example, if your database has articles on quantum tech, it’ll pull the most relevant paragraphs, maybe from recent papers or news sites.</li><li><strong>Augmentation: Mixing It Up</strong>: Now, the retrieved info gets stitched into the prompt for the language model. It’s like saying, “Hey AI, base your answer on THIS specific info: [insert retrieved text here].”</li><li><strong>Generation: Crafting the Response</strong>: Finally, the LLM generates an answer using its training plus the fresh data. The result? More accurate, cited, and up-to-date replies.</li></ol><p>To visualize this process, check out this diagram that shows the flow from query to output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKkq7G3s4mSfLQGTl1BgPg.webp" /><figcaption>Retrieval Augmented Generation (RAG) for LLMs</figcaption></figure><p>See how the retrieval step acts as a bridge? It’s not just generating blindly; it’s informed generation.</p><h3>Real-World Examples of RAG in Action</h3><p>Let’s make this tangible. Suppose you’re building a customer support bot for a tech company. Without RAG, the bot might give generic answers based on old data. With RAG:</p><ul><li>A user asks about a product bug.</li><li>The system retrieves the latest docs, user forums, or internal knowledge base.</li><li>It augments the prompt: “Using this recent fix guide: [details], explain how to resolve the issue.”</li><li>Boom, personalized, accurate help.</li></ul><p>Another cool use: In legal research. Lawyers can query case laws, and RAG pulls exact precedents, reducing hours of manual searching.</p><p>Or in education: A tutoring AI that retrieves textbook excerpts to explain concepts tailored to your question.</p><p>Here’s another helpful illustration breaking down the steps in RAG, which might click if the first one didn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QD_dTpRKS5Ipcdx3XcvlCg.webp" /><figcaption>Understanding RAG: 6 Steps of Retrieval Augmented Generation</figcaption></figure><h3>Why Bother with RAG? The Perks and Pitfalls</h3><p>Pros:</p><ul><li><strong>Accuracy Boost</strong>: Less hallucination since answers are grounded in real data.</li><li><strong>Cost-Effective</strong>: No need to retrain models constantly, just update your knowledge base.</li><li><strong>Scalability</strong>: Handles domain-specific knowledge, like medical or financial info, without bloating the model.</li><li><strong>Privacy-Friendly</strong>: You can use private databases, keeping sensitive data in-house.</li></ul><p>Cons (because nothing’s perfect):</p><ul><li><strong>Setup Hassle</strong>: Building a good retrieval system takes effort, indexing data, handling embeddings.</li><li><strong>Latency</strong>: That extra retrieval step can slow things down a tad.</li><li><strong>Quality Depends on Data</strong>: Garbage in, garbage out. If your database sucks, so will the outputs.</li></ul><p>Overall, though, RAG is a powerhouse for making AI more reliable. Companies like OpenAI and Google are integrating it everywhere.</p><p>For a broader overview, this guide image captures the essence of RAG in a comprehensive way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EL2pPafPyB3wr-ySF4frPA.jpeg" /><figcaption>Retrieval-Augmented Generation (RAG): A Comprehensive Guide</figcaption></figure><h3>Wrapping It Up: Why You Should Care About RAG</h3><p>In simple terms, RAG is like upgrading your AI from a know-it-all with a spotty memory to a diligent researcher who checks facts first. Whether you’re a developer tinkering with apps, a business owner eyeing smarter tools, or just curious about AI’s future, understanding RAG puts you ahead.</p><p>If you’re inspired to try it, start with libraries like LangChain or Haystack, they make implementing RAG a breeze. Experiment, iterate, and who knows? Your next project might revolutionize how we interact with info.</p><p>Thanks for reading! If this sparked questions, drop a comment below. Let’s keep the conversation going.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5aa0279af74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AQFusionNet: What AI Could See (part 1)]]></title>
            <link>https://medium.com/@koushikkushal95/aqfusionnet-what-ai-could-see-part-1-58e3643b9630?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/58e3643b9630</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 09:35:28 GMT</pubDate>
            <atom:updated>2025-08-28T09:35:28.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>A deep learning algorithm to predict the Air Quality Index (AQI) from atmospheric imagery and environmental sensor data.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*in5mLPe7GXydUZjFyQ0_5Q.png" /><figcaption>Heatmap and Prediction</figcaption></figure><p>Have you ever looked up at the sky and wondered if the air you’re breathing is clean? Usually, we rely on sensors to measure pollution levels, but sensors are expensive and not always available everywhere. This is where <strong>AQFusionNet</strong>comes in — a new AI model that can “see” the air quality using both <strong>images of the sky</strong> and <strong>sensor readings</strong>.</p><h3>What Makes AQFusionNet Special?</h3><p>Most air quality systems depend only on sensor data. But AQFusionNet is different:</p><ul><li>It looks at <strong>pictures of the sky or city</strong> (to detect haze, smog, or color changes).</li><li>It also uses <strong>numerical data</strong> like temperature, humidity, and pollution levels.</li><li>If sensor data is missing, the model can still make predictions using just images.</li></ul><p>This makes it smart, flexible, and useful in places where setting up full sensor networks isn’t possible.</p><h3>How It Works (In Simple Words)</h3><p>Think of AQFusionNet as a team:</p><ul><li>One part is good at “looking” at photos.</li><li>Another part is good at “reading numbers.”</li><li>Together, they combine what they see and read to guess the Air Quality Index (AQI). Altogether, build a semantic relationship with image and sensors(CO, SO2, NO2, O3, PM2.5, PM10).</li></ul><p>Even when some information is missing, the team still works together to give a reliable prediction.</p><h3>Why It Matters</h3><ul><li><strong>For cities:</strong> Helps track pollution daily.</li><li><strong>For rural areas:</strong> Provides insights even without sensors.</li><li><strong>For people:</strong> Raises awareness about the air they breathe.</li></ul><h3>The Bigger Picture</h3><p>AQFusionNet shows us how AI can go beyond numbers and actually “see” the world. We hope that this system may have the potential to improve air quality monitoring and increase access to reliable pollution insights globally.Towards this goal, the future of this research will depend on obtaining access to more diverse datasets for training and improving the model, as well as testing it across new geographic regions and environmental conditions.</p><p><strong>Disclaimer</strong>: In the next part we’ll talk about dataset, model approach and code.</p><p><em>If you’d like to dive deeper, feel free to explore my blog and check out my full research paper through the link below.</em></p><p><a href="https://koushikl0l.github.io/AQI.html">AQFusionNet: Deep learning for Air Quality Prediction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58e3643b9630" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Language Model (NLP) Part 1]]></title>
            <link>https://medium.com/@koushikkushal95/recreating-the-classics-with-shakespeare-prose-language-model-nlp-e244bb09e434?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e244bb09e434</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 10:16:22 GMT</pubDate>
            <atom:updated>2023-12-22T14:03:27.932Z</atom:updated>
            <content:encoded><![CDATA[<p>Bigram Language Model with Sequential Text Input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*mxvJoZ-_E1Amv_QhUkMV_Q.png" /><figcaption>BiGram Model Representation. source:author</figcaption></figure><p>In the realm of natural language processing, the journey to predict the next character in a sequence has led us to innovative techniques. This article explores the creation of a powerful bigram language model that gradually feeds in sequential text, evolving from individual characters to comprehensive substrings. The model is equipped with an <strong>embedding layer</strong> and utilizes the prowess of <strong>softmax and sparse categorical crossentropy</strong> for accurate predictions. Let’s unravel the intricacies of predictive text modeling and dive into the world of sequential input.</p><p><strong>Data Preparation —</strong></p><p>Here, we Breaking down the input text into sequential chunks, ranging from single characters to bigrams. This ensures that the model receives a progressively expanding context. Here is an example how we create those chunks and code:</p><pre>x = train_data[:block_size]<br>y = train_data[1:block_size+1]<br>for t in range(block_size):<br>    context = x[:t+1]<br>    target = y[t]<br>    print(f&quot;when input is {context} the target: {target}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MF8ArMkmORSVFcsOWVCimQ.png" /><figcaption>Input/output split. source:author</figcaption></figure><p>For demonstrating purpose we use this example and build an input/output pair to feed into bigram language model. The next step is mapping characters to numerical indices is essential for the model to process the data. Each unique character is assigned a specific index, enabling efficient representation in the neural network. Here is how we can do this:</p><pre>#find out number of character in shakespeare<br>chars = sorted(list(set(text)))<br><br># Convert character to numeric<br>char_to_index = {char: index for index, char in enumerate(chars)}<br># Retrieve numeric and convert to character<br>index_to_char = {index: char for index, char in enumerate(chars)}<br># Encode a string to numeric values<br>def encode(s):<br>    return [char_to_index[c] for c in s]<br># Decode a list of numeric values to a string<br>def decode(l):<br>    return &#39;&#39;.join([index_to_char[i] for i in l])</pre><p><strong>Data Splits and Batch Processing —</strong></p><p>Effective bigram language model involves strategic data splitting and batch processing. These steps are pivotal in ensuring that our model not only learns from diverse examples but also generalizes well to unseen data.In the spirit of robust model training, we partition our dataset into training and validation sets. With a prudent decision to allocate 90% of the data for training and 10% for validation.</p><p><strong>Batch Size (32):</strong> A batch size of 32 signifies that the model processes 32 sequences at a time during each training iteration. This not only accelerates computation but also introduces a degree of stochasticity, helping the model escape local optima and converge more efficiently.</p><p><strong>Block Size (8): </strong>Within each batch, sequences are chunked into groups of 8. This chunking mechanism aids the model in grasping short-term dependencies within sequences, providing a balance between context comprehension and computational efficiency.</p><p><strong>Embedding —</strong></p><p>We’ll feed each input chuck with batches to an embedding layer. The embedding layer used to map the one-hot encoded vectors into continuous vector spaces. Where, <em>V</em> is the size of the vocabulary, and <em>d</em> is the dimensionality of the embedding space. The embedding layer can be represented by a matrix W of size <em>V</em>×<em>d</em>, where each row corresponds to the embedding vector of a particular character. Here, is embedding mechanism with look-up table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlgtpjdUytFTf9Dh3emTSw.png" /><figcaption>Embedding table for each representation. source:author</figcaption></figure><p>For demonstation purpose we created an embedding dim =25 and vocal_size=26. During training, the weights of the embedding layer (W) are learned by the model using backpropagation. The model adjusts the weights to minimize a certain loss function, ensuring that similar words in the input data have similar embeddings. Here, e1….e21,…..,e_n column vector are represented as a learnable weight parameter.</p><p><strong>Process the embedding output:</strong></p><p>The code snippet you provided involves reshaping the output of an embedding layer and then applying the sparse categorical crossentropy loss function during the training process. Let’s break down the operations and provide an explanation in theory.</p><pre>logits = self.token_embedding_table(text)<br>B, T, C = logits.shape #(batch_size, sequence_length, embedding_dimensionality)<br>logits = tf.reshape(logits, (B * T, C))<br>targets = tf.reshape(targets, (B * T,))</pre><p><strong>Reshaping —</strong></p><p>logits is the output of the embedding layer, which typically has the shape batch_size, sequence_length, embedding_dim. The tf.reshape operation is used to flatten the tensor, making it a 2D tensor with dimensions batch_size x sequence_length, embedding_dim This is often done to make it compatible with the requirements of the subsequent layers, especially when dealing with sequence data.</p><p><strong>Operations —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ad7w7oSunPccFO9y" /><figcaption>Sparse Categorical Cross Entropy Loss. source:author</figcaption></figure><pre>#here the operations: column-wise operatoins<br>loss = SparseCategoricalCrossentropy(from_logits=True)(targets, logits)</pre><p>targets is another tensor that represents the true labels for each element in the flattened logits. It is also reshaped to be a 1D tensor with dimensions batch_size, sequence_length. The reshaped logits and targets tensors are then passed to the SparseCategoricalCrossentropy loss function. This function is used to compute the crossentropy loss between the predicted logits and the true labels. The from_logits=True argument indicates that the input values (logits) are not normalized probabilities but raw logits.</p><p><strong>Methods of generating next character —</strong></p><p>The purpose of the generate method seems to be to generate new tokens (characters or words) based on an initial sequence of indices. Here&#39;s a breakdown of the method&#39;s functionality with code:</p><pre>def generate(self, text, max_new_tokens):<br>        for _ in range(max_new_tokens):<br>            logits, _ = self(text)<br>            logits = logits[:, -1, :] #here -1 means we only require last index of block <br>            probs = tf.nn.softmax(logits, axis=-1)<br>            idx_next = tf.random.categorical(tf.math.log(probs), num_samples=1)<br>            text = np.concatenate((text, idx_next.numpy()), axis=1)<br>        return text</pre><p>The generate method is part of a text generation model and aims to create a sequence of new tokens based on an initial sequence of indices (text). In each iteration, the model is invoked to predict the next token, and the logits corresponding to the last position in the sequence are selected. These logits are then passed through a softmax function to obtain probabilities for each possible token.</p><p>The tf.random.categorical function is utilized for random sampling, selecting one index (token) based on the calculated probabilities. This sampled index is concatenated to the existing sequence of indices in each iteration. The process repeats for the specified max_new_tokens. The final output is the extended sequence of indices, representing the generated tokens. The randomness in the sampling process introduces variability in the generated sequences, offering diversity in the model&#39;s output. It&#39;s important to note that post-processing may be required to convert these indices back into meaningful tokens using a vocabulary mapping.</p><p><strong>Output: </strong>After running 4400 epoch with a learning rate 1e-3, we achive this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGFW2PvPpTVm0MUJo8piEQ.png" /></figure><p>Moving forward, this model can be improved by adding few more layer,adding layer_norm and increase the block_size with embedded_dim. In our next article, we will delve deep into the intricacies of the transformer model, providing a comprehensive understanding of its architecture and its transformative impact on language modeling. Thank you for joining us on this journey through language models.</p><p>Here is the <a href="https://github.com/Koushikl0l/BiGram_LM"><em>code</em></a> and <a href="https://github.com/Koushikl0l/BiGram_LM"><em>dataset</em></a>.</p><p>Thank you!</p><p>Feel free to go through my other articles:</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li><li><a href="https://medium.com/@koushikkushal95/mnist-hand-written-digit-classification-using-neural-network-from-scratch-54da85712a06">MNIST(hand written digit) Classification Using Neural Network From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/logistic-regression-from-scratch-dfb8527a4226">Logistic Regression From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/what-class-imbalance-is-all-about-details-with-examples-46d5d9da17b8">What Class Imbalance is all about: details with examples</a></li><li><a href="https://medium.com/@koushikkushal95/recurrent-neural-networks-part-1-78302d544466">Recurrent Neural Networks: Part 1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e244bb09e434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurrent Neural Networks: Part 1]]></title>
            <link>https://medium.com/@koushikkushal95/recurrent-neural-networks-part-1-78302d544466?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78302d544466</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 21:31:58 GMT</pubDate>
            <atom:updated>2023-12-11T22:40:59.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Backbone of Sequential Data Processing</p><p>Recurrent Neural Networks (RNNs) are a type of neural network architecture designed for processing sequential data. They are particularly well-suited for tasks where the order of the input data is crucial, such as natural language processing, time series analysis, and speech recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBr-eHTCQ_tSSpr4u1WUUg.png" /><figcaption>(1)RNN timesteps. source: author</figcaption></figure><p>For each timestep <em>t</em>, the activation <em>y</em>&lt;<em>t</em>&gt;,h&lt;t&gt; and the output are expressed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_jMcfLserB1IeSd9cq9Mw.png" /><figcaption>(2)RNN- single timestep. source:author</figcaption></figure><p><strong><em>How each time-step of RNN work —</em></strong></p><p>RNNs maintain a hidden state that is updated at each time step based on the current input and the previous hidden state. This hidden state serves as a memory, allowing the network to capture information about previous inputs and use it to influence the current prediction. The basic operations in each timestepe as follows:</p><p><strong>Forward Propagation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FWMJvln3fEuUtQ9_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TF5q5eTM6TG-Q-Ql" /></figure><p>where:</p><ul><li><em>ht​</em> is the hidden state at time <em>t</em>,</li><li><em>xt</em>​ is the input at time <em>t</em>,</li><li><em>Whx, Why</em>​ is the weight matrix for the input,</li><li><em>Whh</em>​ is the weight matrix for the hidden state,</li><li><em>bh, by</em>​ is the bias term,</li></ul><p><em>Code single unit RNN—</em></p><pre>   def forward(self, x):<br>        # this list i create  for backpropagation<br>        self.intermediate_values = []<br>        hidden_states = []<br>        outputs = []<br><br>        for t in range(len(x)):<br>            x_t = x[t].reshape(-1, 1)<br><br>            h_t = np.tanh(np.dot(self.W_hx, x_t) + np.dot(self.W_hh, self.h_t) + self.b_h)<br>            y_t = np.dot(self.W_yh, h_t) + self.b_y<br><br>            # Store hidden state and output for this timestep<br>            hidden_states.append(h_t)<br>            outputs.append(y_t)<br>            # Update hidden state for the next timestep<br>            self.h_t = h_t<br>            # Store intermediate values for backpropagation<br>            self.intermediate_values.append((x_t, h_t, y_t))<br><br>        return outputs, hidden_states</pre><p><strong><em>Loss Function</em> — </strong>In the case of a recurrent neural network, the loss function L of all time steps is defined based on the loss at every time step as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2b62VL3DjKXcLon" /></figure><p><strong><em>Backpropagation —</em></strong></p><p><strong><em>1. backpropagation through time for</em> <em>Loss:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ao-IGynVFSKvZmg8" /></figure><p><strong><em>2. backpropagation through time for</em> <em>Whx:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OFi_ehsu0SOgLucg" /></figure><p><strong><em>3. backpropagation through time for</em> <em>Whh:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wZSupNNXunWptqFl" /></figure><p><strong><em>4. backpropagation through time for</em> b<em>h:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGkGMkwQh6DxYyKF" /></figure><p><strong><em>5. backpropagation through time for</em> <em>tanh:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQrk3bwev6L6Onk-" /></figure><pre>def backward(self, x, targets):<br>        # Initialize gradients<br>        dL_dW_hx = np.zeros_like(self.W_hx)<br>        dL_dW_hh = np.zeros_like(self.W_hh)<br>        dL_db_h = np.zeros_like(self.b_h)<br>        dL_dW_yh = np.zeros_like(self.W_yh)<br>        dL_db_y = np.zeros_like(self.b_y)<br><br>        # Initialize gradient of loss with respect to hidden state<br>        dL_dh_t = np.zeros_like(self.h_t)<br><br>        # Backpropagation through time<br>        for t in reversed(range(len(x))):<br>            x_t, h_t, y_t = self.intermediate_values[t]<br>            target_t = targets[t].reshape(-1, 1)<br><br>            # Compute loss gradient with respect to output<br>            dL_dy_t = y_t - target_t #. 1<br><br>            # Compute gradient of loss with respect to hidden state<br>            # dervative of (h_t*w_hy+b_y) with respect of ht<br>            dL_dh_t += np.dot(self.W_yh.T, dL_dy_t) # 2,3,4<br><br>            # Backpropagation through tanh<br>            #derivative of tanh(x) with respect to x is 1- tan**2(x)<br>            dtanh = (1 - h_t**2) * dL_dh_t # 5<br><br>            # Accumulate gradients for the parameters<br>            dL_dW_hx += np.outer(dtanh, x_t)<br>            dL_dW_hh += np.outer(dtanh, h_t)<br>            dL_db_h += dtanh<br>            dL_dW_yh += np.outer(dL_dy_t, h_t)<br>            dL_db_y += dL_dy_t<br><br>            # Update gradient of loss with respect to hidden state for the next timestep<br>            # dervative of (h_t-1*w_hh+b_y) with respect of ht-1<br>            dL_dh_t = np.dot(self.W_hh.T, dtanh)</pre><p>We initialize gradients for each parameter and the gradient of the loss with respect to the hidden state (<em>ht</em>​). We perform backpropagation through time, starting from the last timestep. For each timestep, we compute gradients for the parameters and accumulate the gradient of the loss with respect to the hidden state. The gradients are updated using gradient descent.</p><p><strong><em>Activations that usually use —</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0nEjRVmHc-T4kwWTn287g.png" /><figcaption>(3)Activations.</figcaption></figure><p><strong><em>Training</em></strong> —</p><pre>def train(self, x, targets, epochs):<br>    for epoch in range(epochs):<br>        # Forward pass<br>        outputs, _ = self.forward(x)<br><br>        # Compute and print the loss<br>        loss = 0.5 * np.mean((outputs - targets)**2)<br>        print(f&quot;Epoch {epoch + 1}/{epochs}, Loss: {loss}&quot;)<br><br>        # Backward pass<br>        self.backward(x, targets)</pre><p>We perform training for a specified number of epochs. In each epoch, we perform a forward pass, compute the loss, and print it. We then perform a backward pass to update the model parameters.</p><p><strong>Applications of RNN —</strong></p><p>While recurrent neural networks are depicted in the diagrams above in what is known as feedforward networks, they are not limited in this way. Instead, feedforward networks map one input to one output. Rather, the length of their inputs and outputs can vary, and different kinds of RNNs are employed for various use cases, including machine translation, sentiment analysis, and the creation of music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAJpPSQqq1JKQd3Oq8-Tgg.png" /><figcaption>(4)Applicatiions of RNN. source: Shervine blog</figcaption></figure><p><strong><em>Deep RNN —</em></strong></p><p>Dealing with deep recurrent neural networks (RNNs), you have multiple options for designing and implementing the architecture. One common approach is to stack multiple layers of RNNs, creating a deep RNN architecture. Here’s a explanation of how to design a deep RNN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DcjVzpSSJwVGopBPnCLmxA.png" /><figcaption>Deep RNN. source: Stanford University</figcaption></figure><p><em>Stacking RNN Layers —</em></p><ul><li>You can stack multiple RNN layers on top of each other to create a deep architecture.</li><li>Each layer in the stack processes the input sequence sequentially, and its hidden state is passed as input to the next layer.</li><li>The output of the top layer is often used for making predictions or further processing.</li></ul><p>Deep RNNs can be computationally intensive, and training might take longer. Techniques like batch normalization or layer normalization can be beneficial for training deeper networks. You might also consider using more advanced RNN architectures like LSTM or GRU to address the vanishing/exploding gradient problem.</p><p><em>In the next article we’ll delve into LSTM, GRU, vanishing/exploding gradient.</em></p><p>Thank You!</p><p>Feel free to visit my previous articles</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/understanding-federated-learning-advancing-machine-learning-while-protecting-privacy-c60257da096a">Federated Learning: Advancing Machine Learning While Protecting Privacy.</a></li><li><a href="https://medium.com/@koushikkushal95/beyond-pixels-mastering-advanced-image-processing-in-computer-vision-e903535440a5">Computer Vision: Advanced Image Processing all You Need.</a></li><li><a href="https://medium.com/@koushikkushal95/optimization-algorithms-in-machine-learning-a-comprehensive-guide-to-understand-the-concept-and-3db1df7a2f59">Optimization Algorithms in Machine Learning: A Comprehensive Guide to Understand the concept and…</a></li><li><a href="https://medium.com/@koushikkushal95/unfolding-the-intelligence-machine-learning-vs-deep-learning-d8165fb70f0b">Unfolding the Intelligence: Machine Learning vs. Deep Learning</a></li></ul><p>References</p><ul><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwiUyOzWp4iDAxVhcGwGHTjiANwQFnoECBcQAQ&amp;url=https%3A%2F%2Fopenlearninglibrary.mit.edu%2Fcourses%2Fcourse-v1%3AMITx%2B6.036%2B1T2019%2Fjump_to%2Fblock-v1%3AMITx%2B6.036%2B1T2019%2Btype%40sequential%2Bblock%40rnn&amp;usg=AOvVaw2uOr0r1HOJ2poLuQ0xPyfk&amp;opi=89978449">Introduction to Machine Learning</a></li><li><a href="https://stanford.edu/~shervine/teaching/cs-230/cheatsheet-recurrent-neural-networks">CS 230 - Recurrent Neural Networks Cheatsheet</a></li><li><a href="https://developer.ibm.com/learningpaths/supervised-deep-learning/recurrent-neural-networks/introduction-recurrent-neural-networks">IBM Developer</a></li><li><a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">Recurrent neural network - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78302d544466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Advanced Image Processing all You Need.]]></title>
            <link>https://medium.com/@koushikkushal95/beyond-pixels-mastering-advanced-image-processing-in-computer-vision-e903535440a5?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e903535440a5</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 18:45:22 GMT</pubDate>
            <atom:updated>2023-12-23T08:53:11.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Unraveling the Mathematics of Image Processing for Enhanced Computer Vision</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*MmzLS6pXYWcXNmjND_BcuA.jpeg" /><figcaption>Feature Extraction. source: <a href="https://learnopencv.com/image-recognition-and-object-detection-part1/">Satya Mallick</a></figcaption></figure><p>In computer vision, feature extraction plays a pivotal role in transforming raw input data, such as images, into a format that is more amenable to analysis and understanding. Feature extraction involves identifying and selecting relevant information or features from the input data. These features capture distinctive patterns, structures, or characteristics of the data, making it easier for algorithms to interpret and make decisions. The primary purposes of feature extraction in computer vision include:</p><ol><li><strong>Dimensionality Reduction:</strong> Feature extraction often reduces the dimensionality of the data by representing it in a more compact and meaningful form. This reduction facilitates more efficient processing and storage of information.</li><li><strong>Highlighting Relevant Information:</strong> Features extracted from images highlight specific aspects of interest, such as edges, corners, textures, or key points. These features are critical for tasks like object recognition, image classification, and scene understanding.</li><li><strong>Enhancing Robustness:</strong> By focusing on essential features, computer vision algorithms become more robust to variations in lighting conditions, viewpoint changes, and other factors that can affect the appearance of objects in images.</li><li><strong>Enabling Discrimination:</strong> Extracted features serve as discriminative elements that distinguish between different objects or classes. They capture unique aspects of the data that contribute to accurate identification and classification.</li><li><strong>Preparing Data for Machine Learning:</strong> Feature extraction is a crucial step in preparing data for machine learning models. By representing images with relevant features, the learning algorithms can better generalize patterns and relationships within the data.</li><li><strong>Improving Computational Efficiency:</strong> Extracting relevant features reduces the computational load on subsequent processing steps. It allows algorithms to focus on the most informative aspects of the data, leading to faster and more efficient computations.</li></ol><p>Let’s delve deeper into the theoretical aspects of some feature extraction methods:</p><h3><strong>Edge Detection:</strong></h3><p>Edge detection aims to identify regions in an image where there is a significant change in intensity. Edges often represent object boundaries or important structures within the image. The Canny edge detector is a popular method that involves multiple steps, including gradient calculation, non-maximum suppression, and edge tracking by hysteresis.</p><p>Edge detection often involves computing the gradient of the image intensity. The gradient (∇<em>f</em>) of an image <em>f</em>(<em>x</em>,<em>y</em>) is computed using convolution with derivative filters (e.g., Sobel or Prewitt operators):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*TGXXTIoJx5N8EIYdWXYXXg.png" /><figcaption>Gradient derivative filters. source: author</figcaption></figure><p>The magnitude of the gradient (<em>M</em>) is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*V4oYyiIQjwe3AMoY4brVYQ.png" /><figcaption>Calculate Gradient Magnitude</figcaption></figure><p>and the direction (<em>θ</em>) is determined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*y8GF_PzlL9eMgw4UQj6WdA.png" /></figure><p>The Canny edge detector further involves non-maximum suppression and hysteresis thresholding. Let’s deep dive how it functions.</p><p><strong>Non-Maximum Suppression:</strong></p><p>After computing the gradient magnitude (<em>M</em>) and direction (<em>θ</em>) for each pixel, non-maximum suppression is applied to thin the edges and keep only the local maxima in the gradient direction. The idea is to ensure that the detected edges have a clear and sharp response along the gradient direction.</p><p>For each pixel, non-maximum suppression involves comparing the gradient magnitude of the pixel with its neighbors in the gradient direction. If the gradient magnitude at the pixel is greater than its neighbors, it is retained; otherwise, it is suppressed.</p><p>Let <em>M</em>(<em>x</em>,<em>y</em>) be the gradient magnitude, and <em>θ</em>(<em>x</em>,<em>y</em>) be the gradient direction at pixel (<em>x</em>,<em>y</em>). The non-maximum suppression can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyuTvAt3v4GmRYZmxj7xJg.png" /></figure><p>Here, <em>M</em>1​ and <em>M</em>2​ are the gradient magnitudes of the two neighboring pixels along the gradient direction.</p><p><strong>Hysteresis Thresholding:</strong></p><p>Hysteresis thresholding is applied to distinguish between strong edges, weak edges, and noise. It involves setting two threshold values: a high threshold (<em>T</em>high​) and a low threshold (<em>T</em>low​). Pixels with gradient magnitudes above <em>T</em>high​ are considered strong edges, while pixels between <em>T</em>low​ and <em>T</em>high​ are considered weak edges.</p><p>The algorithm then traces along the strong edges and connects weak edges to the strong edges if they form a continuous path. This helps in preserving edges while suppressing noise.</p><p>hysteresis thresholding can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*2t4ZPtUnCw8g_WurLtPNFg.png" /></figure><p>This process is typically implemented using depth-first search or similar techniques to trace and connect the weak edges forming a coherent edge map.</p><p>In summary, non-maximum suppression ensures that only local maxima in the gradient direction are retained, and hysteresis thresholding helps in distinguishing strong edges from weak edges and connecting them to form a more robust edge map.</p><h3>Corner Detection (Harris Corner Detection):</h3><p><strong>Structure Tensor Calculation:</strong></p><p>For a given pixel (<em>x</em>,<em>y</em>), the first step is to calculate the structure tensor <em>M</em>, which is a 2x2 matrix representing local intensity changes in the image. The structure tensor is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*QrLYKVdkkNQ6vBhtO7lIng.png" /><figcaption>Tensor Calculation</figcaption></figure><p>where <em>Ix</em>​ and <em>Iy</em>​ are the image gradients at pixel (<em>x</em>,<em>y</em>), and <em>w</em>(<em>x</em>′,<em>y</em>′) is a window function centered at (<em>x</em>,<em>y</em>).</p><p><strong>Corner Response Function:</strong></p><p>The corner response function <em>R</em> is computed from the eigenvalues (<em>λ</em>1​ and <em>λ</em>2​) of the structure tensor <em>M</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*5CqFMlmRD6f-hqhIE4MaUA.png" /><figcaption>Corner response function</figcaption></figure><p>Here, det(<em>M</em>) is the determinant of <em>M</em>, trace(<em>M</em>) is the trace of <em>M</em>, and <em>k</em> is an empirically determined constant (typically in the range of 0.04 to 0.06).</p><p><strong>Corner Identification:</strong></p><p>After computing the corner response function for each pixel, corners are identified by selecting pixels with high corner response values. A common approach is to threshold the corner response function and consider pixels with response values above a certain threshold as corners</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*QgfGRh9yh5_efXr81AZZAw.png" /><figcaption>Corner identification</figcaption></figure><h3>Texture Analysis</h3><p>Local Binary Patterns (LBP) is a texture analysis method that captures the local patterns of pixel intensities in an image. It is particularly useful for characterizing textures and patterns in images. Here’s a detailed explanation of LBP:</p><p>For a given pixel (<em>x</em>,<em>y</em>), LBP is calculated by comparing the intensity of the center pixel with the intensities of its neighboring pixels. The binary pattern is generated by assigning a value of 1 to a neighboring pixel if its intensity is greater than or equal to that of the center pixel; otherwise, a value of 0 is assigned. This process is repeated for all neighbors in a predefined circular neighborhood.</p><p>Let <em>P</em> be the number of sampling points in the neighborhood, and <em>R</em> be the radius of the circular neighborhood. The LBP value for a pixel (<em>x</em>,<em>y</em>) is computed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*sShFQrrWUsak6jVIFVnSYQ.png" /></figure><p>Here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*2ox6faSMZDX26eMfjndU5Q.png" /></figure><h3>Color Histogram</h3><p>A color histogram represents the distribution of color intensities in an image. It provides a quantitative description of the colors present in the image, which can be useful for various computer vision tasks.</p><p><strong>Color Space Conversion:</strong></p><p>Before computing the color histogram, the image is typically converted to a color space that separates its color channels. Common color spaces include RGB (Red, Green, Blue), HSV (Hue, Saturation, Value), or LAB (CIELAB). Let’s assume RGB for this explanation.</p><p><strong>Binning:</strong></p><p>In a color histogram, the color space is divided into a set of bins or discrete intervals. Each bin corresponds to a range of color intensities. The number of bins determines the granularity of the histogram. For example, if we use 256 bins for each color channel in the RGB space, we cover all possible intensities (0 to 255).</p><p><strong>Calculation of Histogram:</strong></p><p>For each pixel in the image, the color values are quantized into the corresponding bins. The count of pixels falling into each bin is accumulated to form the histogram.</p><p>Mathematically, let <em>H</em>(<em>ci</em>​) be the histogram for color channel <em>i</em>, where <em>i</em> can be red (R), green (G), or blue (B). The histogram is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*VpgtQLOQIQ4d3PnbvENBvQ.png" /><figcaption>Color quantisation of each channel</figcaption></figure><p>Here:</p><ul><li><em>N</em> is the number of bins.</li><li><em>δ</em> is the Dirac delta function, which equals 1 when <em>ci</em>​ falls within the <em>j</em>-th bin, and 0 otherwise.</li></ul><h3>Histogram of Oriented Gradients (HOG):</h3><p>Histogram of Oriented Gradients (HOG) is a feature descriptor widely used in computer vision for object detection. It captures information about the local gradient directions in an image. The HOG algorithm involves the following steps:</p><p>For each pixel in the image, compute the <strong>gradient magnitude</strong> and orientation. This can be done using convolution with Sobel filters or any other gradient calculation method. Follow the earlier explanation of <strong>edge detection </strong>and compute G: gradient magnitude, and <em>θ: </em>gradient orientation.</p><p>Divide the image into small cells (e.g., 8x8 pixels). Each cell contains a local histogram of gradient orientations. For each cell, calculate a histogram of gradient orientations. The histogram is created by accumulating the gradient magnitudes into bins based on their orientations. Group cells into larger blocks (e.g., 2x2 cells). Normalize the histograms within each block to improve invariance to changes in illumination and contrast. Concatenate the normalized histograms from all blocks to form the final HOG descriptor for the image.</p><p><strong>Mathematically:</strong></p><p>Let <em>M</em> be the number of cells, <em>N</em> be the number of bins in the histogram, and <em>B</em> be the number of blocks. The HOG descriptor <em>H</em> is formed as follows:</p><p><em>H</em>=[<em>H</em>1​,<em>H</em>2​,…,<em>HB</em>​]</p><p>where each <em>Hb</em>​ is the normalized histogram for block <em>b</em>. The normalization is often done using the L2-norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*sUB232OHbQhIjumtl84jMQ.png" /></figure><p>Here, <em>ϵ</em> is a small constant added to the denominator to avoid division by zero.</p><p>The HOG descriptor can be used for various computer vision tasks, such as object detection and pedestrian recognition.</p><h3>Principal Component Analysis (PCA)</h3><p>PCA is a dimensionality reduction technique used to transform high-dimensional data into a lower-dimensional space while retaining the most important information. It is commonly applied to image data, feature vectors, or any dataset where reducing dimensionality is beneficial.</p><p>PCA begins by mean-centering the data, ensuring that the mean of each feature is zero. Calculate the covariance matrix to understand the relationships between different features. Find the eigenvectors and eigenvalues of the covariance matrix. Select the top <em>K</em> eigenvectors corresponding to the largest eigenvalues. Sort the eigenvalues in descending order, and choose the top <em>K</em> eigenvectors to form the matrix. Project the mean-centered data onto the subspace spanned by the selected principal components.</p><h3>Key Concepts:</h3><ul><li>Eigenvalues and Eigenvectors: Eigenvalues represent the amount of variance along the corresponding eigenvector direction. Larger eigenvalues indicate directions with more significant variability.</li><li>Principal Components: Principal components are the eigenvectors of the covariance matrix. Each principal component represents a direction in the original feature space.</li><li>Variance Retention: PCA allows the user to choose the number of principal components to retain, based on the desired amount of variance to be preserved in the data.</li><li>Dimensionality Reduction: The dimensionality of the data is reduced from <em>D</em> to <em>K</em> dimensions (<em>K</em>≤<em>D</em>).</li></ul><p>PCA is a valuable tool for preprocessing data, reducing noise, and improving the efficiency of machine learning algorithms, especially when dealing with high-dimensional datasets.</p><h3>Entropy</h3><p>Shannon Entropy, named after Claude Shannon, is a measure of uncertainty or information content in a set of data. In the context of information theory, it quantifies the average amount of surprise or unpredictability associated with the outcomes of a random variable.</p><p>The formula for Shannon Entropy (<em>H</em>) for a discrete random variable with probability distribution <em>P</em>(<em>x</em>) is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*7pmUFhRIkPJix199_RXWhg.png" /><figcaption>Shannon’s Entropy</figcaption></figure><p>Here:</p><ul><li><em>xi</em>​ represents each possible outcome of the random variable <em>X</em>.</li><li><em>P</em>(<em>xi</em>​) is the probability of occurrence of <em>xi</em>​.</li><li>The sum is taken over all possible outcomes.</li></ul><p><strong>Interpretation:</strong> Higher entropy indicates higher uncertainty or disorder in the data, while lower entropy suggests more predictability.</p><p><strong>Units:</strong> Entropy is measured in bits if the logarithm is base 2. In practice, the base of the logarithm depends on the unit of measurement for the probabilities (e.g., natural logarithm for base e<em>e</em> or base 10 logarithm).</p><p><strong>Entropy in Information Theory:</strong> In information theory, entropy is used to quantify the average number of bits needed to represent the information content of a message or the average “surprise” associated with receiving a symbol from a source.</p><p>In the context of images, Shannon Entropy can be used to measure the amount of information or complexity in the pixel intensities. Images with more uniform pixel intensities across the image may have lower entropy, while images with varied intensities may have higher entropy.</p><p>Apply feature extraction methods as a preprocessing step before training machine learning models. Ensure that the selected features align with the requirements of the specific task. Integrate the extracted features as input to machine learning models (e.g., SVM, Random Forest, Neural Networks). Fine-tune hyperparameters based on the characteristics of the extracted features.</p><p>In summary, feature extraction is a crucial step in the machine learning pipeline, enhancing the model’s ability to generalize and perform well on diverse datasets. The choice of feature extraction method depends on the characteristics of the data and the specific requirements of the machine learning task.</p><p>The code will be available this <a href="https://github.com/Koushikl0l/Writings_/tree/main">github</a> repository soon.</p><p>Thank You!</p><p>Follow my previous articles.</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/optimization-algorithms-in-machine-learning-a-comprehensive-guide-to-understand-the-concept-and-3db1df7a2f59">Optimization Algorithms in Machine Learning: A Comprehensive Guide to Understand the concept and…</a></li><li><a href="https://medium.com/@koushikkushal95/understanding-federated-learning-advancing-machine-learning-while-protecting-privacy-c60257da096a">Federated Learning: Advancing Machine Learning While Protecting Privacy.</a></li></ul><p>References.</p><ul><li><a href="https://learnopencv.com/image-recognition-and-object-detection-part1/">Image Recognition and Object Detection : Part 1</a></li><li><a href="https://www.ibm.com/topics/computer-vision">What is Computer Vision? | IBM</a></li><li><a href="https://domino.ai/blog/feature-extraction-and-image-classification-using-deep-neural-networks">Feature extraction and image classification using OpenCV</a></li><li><a href="https://docs.opencv.org/4.x/db/d27/tutorial_py_table_of_contents_feature2d.html">OpenCV: Feature Detection and Description</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e903535440a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Federated Learning: Advancing Machine Learning While Protecting Privacy.]]></title>
            <link>https://medium.com/@koushikkushal95/understanding-federated-learning-advancing-machine-learning-while-protecting-privacy-c60257da096a?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60257da096a</guid>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 19:51:19 GMT</pubDate>
            <atom:updated>2023-12-08T01:46:47.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Revolutionizing Machine Learning Through Decentralized Collaboration and Data Confidentiality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*CMcNdGuCe-vM_A2SLalh1w.png" /><figcaption>Federated learning mechanism. source: Arun</figcaption></figure><p>Federated Learning is a revolutionary approach in the realm of machine learning that addresses the challenges of privacy, security, and data decentralization. In traditional machine learning, data is centralized on a server, which raises concerns about privacy breaches and data security. Federated Learning overcomes these issues by enabling model training on decentralized devices while keeping raw data on those devices. This article delves into the details of federated learning, its applications, advantages, and how it is shaping the future of machine learning.</p><p><strong>Why Federated Learning??</strong></p><p><strong>Privacy Preservation:</strong> One of the key motivations behind federated learning is privacy preservation. By keeping data localized, federated learning reduces the risk of exposing sensitive information. Users have greater control over their data, and the need for trusting a central authority with large datasets is diminished. This makes federated learning particularly attractive in applications where data privacy is paramount, such as healthcare, finance, and personal devices.</p><p><strong>Decentralized Training:</strong> In federated learning, the training process takes place locally on individual devices or servers. The model is sent to these devices, and each device computes the model updates based on its local data.</p><p><strong>Edge Computing: </strong>Federated learning is well-suited for edge computing environments, where devices at the edge of the network (e.g., IoT devices, smartphones) can collaboratively train models without relying on a centralized server</p><h3><strong>Applications:</strong></h3><p><strong>Photo and Video Organization:</strong></p><ul><li><em>Description:</em> Applications that automatically organize photos or videos on a user’s device may use federated learning for better categorization.</li><li><em>Implementation:</em> The local model learns from the user’s organization patterns, such as facial recognition and location data. Model updates are sent to the central server, aggregated, and an improved global model is distributed for more accurate organization suggestions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*T5iq9puYEOoj0VJ0OGfpWw.png" /><figcaption>Categorisation Google Photos. source: <a href="https://www.businessinsider.com/how-google-created-the-worlds-smartest-photo-app-2015-6">Business Insider</a></figcaption></figure><p><strong>Personalised News Feeds:</strong></p><ul><li><em>Description:</em> Apps that curate news or content feeds often employ federated learning to tailor recommendations based on individual reading preferences.</li><li><em>Implementation:</em> The local model on the user’s phone learns from their reading history, preferences, and interactions. Periodically, model updates are sent to the central server, aggregated, and a more personalized global model is distributed to enhance content recommendations.</li></ul><p><strong>Autocorrect and Predictive Text:</strong></p><ul><li><em>Description:</em> Many mobile keyboards use federated learning to improve autocorrect and predictive text features. The model learns from individual typing patterns, commonly misspelled words, and preferred phrases.</li><li><em>Implementation:</em> The local model on the user’s phone is trained based on their typing history. Periodically, the model updates are sent to the central server, aggregated with other users’ models, and a refined global model is distributed back to improve typing suggestions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*u3Bzi_EYRa-ZyT41kgEypA.png" /><figcaption>Gboard v8.2 auto correction and suggestion</figcaption></figure><p><strong>Challenges and Considerations:</strong></p><ul><li><strong><em>Non-IID Data:</em></strong> Federated Learning assumes that local datasets are independent and identically distributed (IID). In real-world scenarios, this assumption may not hold, posing challenges for model convergence.</li><li><strong><em>Communication Overhead:</em></strong> While federated learning reduces data transmission, there is still communication overhead between the local devices and the central server, especially in large-scale deployments</li></ul><p><strong>Frameworks and Tools:</strong></p><ul><li><em>PySyft:</em> A Python library for federated learning that extends popular deep learning frameworks like PyTorch and TensorFlow.</li><li><em>TensorFlow Federated (TFF):</em> An open-source framework by Google for federated learning with TensorFlow.</li></ul><p><strong>Let’s see how we can code it:</strong></p><p><strong>Dataset:</strong></p><p>The dataset used in this code is a synthetic federated dataset created for the purpose of illustration. It consists of text sequences, each representing a pair of input and target sequences. The input sequences are in English, and the corresponding target sequences are in Spanish. Each client (represented by client_data) contributes a pair of text sequences. The test dataset (test_data) is a small set of sequences used to evaluate the performance of the federated model.</p><pre>def create_federated_data():<br>    <br>    client_data = [<br>        ([&quot;hello&quot;, &quot;world&quot;, &quot;how&quot;, &quot;are&quot;, &quot;you&quot;], [&quot;hola&quot;, &quot;mundo&quot;, &quot;cómo&quot;, &quot;estás&quot;, &quot;tu&quot;]),<br>        ([&quot;good&quot;, &quot;morning&quot;, &quot;federated&quot;, &quot;learning&quot;], [&quot;buenos&quot;, &quot;días&quot;, &quot;aprendizaje&quot;, &quot;federado&quot;]),<br>        ([&quot;federated&quot;, &quot;learning&quot;, &quot;is&quot;, &quot;powerful&quot;], [&quot;aprendizaje&quot;, &quot;federado&quot;, &quot;es&quot;, &quot;poderoso&quot;]),<br>        ([&quot;hello&quot;, &quot;from&quot;, &quot;client&quot;, &quot;four&quot;], [&quot;hola&quot;, &quot;desde&quot;, &quot;cliente&quot;, &quot;cuatro&quot;])<br>    ]<br><br>    train_data = [tf.data.Dataset.from_tensor_slices((x, y)) for x, y in client_data]<br><br>  <br>    test_data = tf.data.Dataset.from_tensor_slices(([&quot;hello&quot;, &quot;world&quot;, &quot;from&quot;, &quot;test&quot;, &quot;set&quot;],<br>                                                    [&quot;hola&quot;, &quot;mundo&quot;, &quot;desde&quot;, &quot;conjunto&quot;, &quot;prueba&quot;]))<br><br>    return train_data, test_data<br><br>train_data, test_data = create_federated_data()</pre><p><strong>Model:</strong></p><p>The model used in this code is a simple autocorrect model implemented as a subclassed neural network using TensorFlow and Keras. The <strong>autocorrect model</strong> class defines a model with an embedding layer, an LSTM layer, and a dense layer with softmax activation. This model is designed to learn the patterns in the input sequences and predict the correct next word in a sequence, similar to an autocorrect mechanism. The architecture of the model is adjustable through parameters like <strong>vocabulary size, embedding dimension, and LSTM</strong> units.</p><pre>import tensorflow as tf<br>import tensorflow_federated as tff<br><br><br>class AutocorrectModel(tf.keras.Model):<br>    def __init__(self, vocab_size, embedding_dim, lstm_units):<br>        super(AutocorrectModel, self).__init__()<br>        self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)<br>        self.lstm = tf.keras.layers.LSTM(lstm_units)<br>        self.dense = tf.keras.layers.Dense(vocab_size, activation=&#39;softmax&#39;)<br><br>    def call(self, inputs):<br>        x = self.embedding(inputs)<br>        x = self.lstm(x)<br>        return self.dense(x)<br><br># TFF learning model<br>def model_fn():<br>    vocab_size = 10000  # Adjust based on your vocabulary size<br>    embedding_dim = 32<br>    lstm_units = 64<br><br>    model = AutocorrectModel(vocab_size, embedding_dim, lstm_units)<br>    return tff.learning.from_keras_model(<br>        model,<br>        input_spec=train_data[0].element_spec,<br>        loss=tf.keras.losses.SparseCategoricalCrossentropy(),<br>        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]<br>    )</pre><p><strong>Evaluation and Goal:</strong></p><p>The goal of this code is to demonstrate federated learning in the context of an autocorrect model. Federated learning is a machine learning approach where the model is trained across multiple decentralized clients, and the training process happens locally on each client. The federated model is then aggregated to produce a global model that benefits from the knowledge learned on each client.</p><pre># Build the Federated Averaging process<br>fed_avg = tff.learning.build_federated_averaging_process(model_fn)<br><br># Training the federated model<br>state = fed_avg.initialize()<br>for round_num in range(5):  # 5 rounds of federated training<br>    state, metrics = fed_avg.next(state, train_data)<br>    print(f&#39;Round {round_num}: {metrics}&#39;)<br><br># Evaluate the federated model on a test dataset<br>evaluation = tff.learning.build_federated_evaluation(model_fn)<br>test_metrics = evaluation(state.model, test_data)<br>print(f&#39;Test Metrics: {test_metrics}&#39;)</pre><p>Specifically, the steps in this code include:</p><ol><li>Defining autocorrect model.</li><li>Setting up a federated learning model using TensorFlow Federated.</li><li>Training the federated model using the Federated Averaging process.</li><li>Evaluating the federated model on a test dataset.</li></ol><p>In summary, federated Learning stands at the forefront of privacy-preserving machine learning, offering a solution to the challenges posed by centralised data storage. As technology advances, federated learning is likely to play a crucial role in shaping the future of machine learning applications across diverse domains, providing a secure and privacy-centric approach to collaborative model training.</p><p>Thank you!</p><p>Feel free to go through my other articles:</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/optimization-algorithms-in-machine-learning-a-comprehensive-guide-to-understand-the-concept-and-3db1df7a2f59">Optimization Algorithms in Machine Learning: A Comprehensive Guide to Understand the concept and…</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li><li><a href="https://medium.com/@koushikkushal95/mnist-hand-written-digit-classification-using-neural-network-from-scratch-54da85712a06">MNIST(hand written digit) Classification Using Neural Network From Scratch</a></li></ul><p>References</p><ul><li><a href="https://research.ibm.com/blog/what-is-federated-learning">What is federated learning?</a></li><li><a href="https://www.tensorflow.org/federated/federated_learning">Federated Learning | TensorFlow Federated</a></li><li><a href="https://blogs.nvidia.com/blog/what-is-federated-learning/">What Is Federated Learning?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60257da096a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimization Algorithms in Machine Learning: A Comprehensive Guide to Understand the concept and…]]></title>
            <link>https://medium.com/@koushikkushal95/optimization-algorithms-in-machine-learning-a-comprehensive-guide-to-understand-the-concept-and-3db1df7a2f59?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db1df7a2f59</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 23:56:05 GMT</pubDate>
            <atom:updated>2023-12-06T23:56:05.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimization Algorithms in Machine Learning: A Comprehensive Guide to Understand the concept and Implementation.</h3><p><strong>Optimizer, </strong>the engine of machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkOrihXKkGR7D19bMweF0Q.png" /><figcaption>gradient descent. source:dmitrijskass</figcaption></figure><p><strong>Definition</strong>: In the context of machine learning, optimization refers to the process of adjusting the parameters of a model to minimize (or maximize) some objective function. The objective function is often a measure of how well the model performs on a task, such as minimizing the error on a set of training data. The process involves finding the optimal set of parameters that result in the best performance of the model.</p><p>There are various optimization algorithms used in machine learning to find the optimal set of parameters. These algorithms are responsible for updating the model parameters iteratively during the training process. Some common optimization algorithms include:</p><p><strong>Gradient Descent</strong>: Gradient Descent is a first-order iterative optimization algorithm widely used in machine learning and optimization problems. Its primary purpose is to minimize a differentiable cost or loss function by iteratively adjusting the parameters of a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16uR2JPzCtu2qSCGPe7kbw.jpeg" /></figure><p><em>w = w</em> − <em>α * δl</em>oss​/<em>δw</em></p><p>Start with an initial set of parameter values (weights) for the model. In each iteration, compute the gradient of the loss function with respect to the parameters. where <em>w </em>represents the parameters, <em>α</em> is the learning rate, and <em>δl</em>oss​/<em>δw</em> is the gradient of the objective function. Simplify the function you would like to minimize by using the first-order polynomial. This expression <em>δl</em>oss/<em>δw </em>represents the rate of change of the loss with respect to the weight parameter and is a crucial component in optimization algorithms like gradient descent. The goal is to adjust the weights in the direction that minimizes the loss, and the derivative provides information about the slope of the loss function at a specific point in the parameter space.</p><p><strong>Objective</strong>: Gradient Descent aims to find the minimum of a cost or loss function. This function represents the difference between the predicted values of the model and the actual values (labels) in a training dataset.</p><p><strong>Convergence and Challenges: </strong>Convergence is achieved when the algorithm reaches a point where further iterations do not significantly change the parameters. However, challenges such as choosing an appropriate learning rate and dealing with <strong>saddle points</strong> and <strong>local minima</strong> can affect convergence.</p><p>Let’s see how to code it.</p><pre>import numpy as np<br><br>def gradient_descent(X, y, w, learning_rate, iterations):<br>    m = len(y)<br>    <br>    for _ in range(iterations):<br>        predictions = np.dot(X, w)<br>        errors = predictions - y<br>        gradient = np.dot(X.T, errors) / m<br>        # α = learning_rate and gradient = δloss​/δw<br>        w = w - learning_rate * gradient<br>    <br>    return w</pre><p><strong>Stochastic Gradient Descent (SGD):</strong></p><p>Stochastic Gradient Descent (SGD) is an optimization algorithm used in machine learning and deep learning for training models. It is an extension of the standard gradient descent algorithm, where instead of computing the gradient of the entire dataset, SGD computes the gradient and updates the model parameters for each training example individually or in small batches.</p><p><strong>Why Use SGD:</strong></p><p><strong>Computational Efficiency: </strong>Computing the gradient using the entire dataset can be computationally expensive, especially for large datasets. SGD allows for more frequent updates with lower computational cost.</p><p><strong>Faster Convergence: </strong>Since updates are made more frequently, SGD often converges faster than traditional gradient descent, especially when dealing with non-convex loss functions.</p><p><strong>Memory Efficiency: </strong>Working with individual or mini-batches of data requires less memory compared to the entire dataset, making SGD suitable for cases where memory is a constraint.</p><p><strong>Escape Local Minima: </strong>The stochastic nature of SGD introduces randomness in the optimization process, helping the algorithm escape local minima and explore the parameter space more effectively.</p><p>It’s an extension of gradient descent where the parameters are updated using a single randomly chosen data point at a time, making it computationally less expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*pwOogJC9AI8l6BkB0_tVQA.png" /><figcaption>Stochastic gradient descent</figcaption></figure><p>where <strong><em>i</em></strong> represents the randomly chosen data point. Let’s see how to code it.</p><pre>import numpy as np<br><br>def stochastic_gradient_descent(X, y, theta, learning_rate, iterations):<br>    m = len(y)<br>    <br>    for _ in range(iterations):<br>        for i in range(m):<br>            rand_index = np.random.randint(0, m)<br>            X_i = X[rand_index, :].reshape(1, -1)<br>            y_i = y[rand_index]<br>            prediction = np.dot(X_i, theta)<br>            error = prediction - y_i<br>            gradient = X_i.T * error<br>            theta = theta - learning_rate * gradient<br>    <br>    return theta</pre><p>In summary, SGD is advantageous for its computational efficiency, faster convergence, and ability to handle large datasets. However, it introduces variance in updates, and the choice of an appropriate learning rate is crucial to balance exploration and exploitation during optimization. The decision to use traditional gradient descent or SGD depends on factors such as dataset size, computational resources, and the nature of the optimization problem.</p><p><strong>RMSprop (Root Mean Square Propagation): </strong>RMSprop is an optimization algorithm designed to address some of the limitations of traditional gradient descent, especially when dealing with non-convex and poorly conditioned optimization problems. It is particularly useful for problems with sparse data and helps to adaptively adjust the learning rates for different parameters.</p><p><strong>How RMSprop Works:</strong> RMSprop adapts the learning rates of each parameter individually by dividing the learning rate by the root mean square of recent gradients. This allows the algorithm to automatically decrease the learning rate for parameters that have steep and rapidly changing gradients and increase the learning rate for parameters with small or slowly changing gradients.</p><p>Algorithm gist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ofAFwbYpiA-9ym5y7SLLcw.png" /></figure><pre>def RmsProp(X, y, theta, learning_rate, beta=.9, iterations, epsilon=1e-7):<br><br>    v_t = np.zeros_like(theta)<br>    # RMSprop optimization loop<br>    for _ in range(iterations):<br>        # Compute the gradient of the loss function<br>        predictions =  X.dot(theta)<br>        errors = predictions - y<br>        gradient = X.T.dot(errors) / len(y)<br>    <br>        # Update the exponentially decaying average of squared gradients<br>        v_t = beta * v_t + (1 - beta) * gradient**2<br>    <br>        # Update the parameters using RMSprop<br>        theta -= (learning_rate / (np.sqrt(v_t) + epsilon)) * gradient<br><br>    return theta</pre><p>In summary, RMSprop helps mitigate issues like slow convergence and oscillations in the learning rate by adapting the learning rates for each parameter based on the historical gradients. It is a popular choice in practice, especially for training deep neural networks, and can be particularly effective in scenarios where the landscape of the optimization problem is challenging or has varying curvature. The algorithm provides a balance between the aggressive adaptability of methods like AdaGrad and the more stable behavior of methods like SGD.</p><p><strong>Adam (Adaptive Moment Estimation): </strong>Adam is an optimization algorithm used for training machine learning models. It combines ideas from both momentum optimization and RMSprop (Root Mean Square Propagation). Adam adapts the learning rates for each parameter individually based on the historical gradients of those parameters.</p><p><strong>Why Adam ??</strong></p><p><strong>Adaptive Learning Rates:</strong> One of the key advantages of Adam is its adaptive learning rate mechanism. It adjusts the learning rates for each parameter based on the historical gradients, allowing it to perform well across different types of parameters and features.</p><p><strong>Efficiency in Sparse Gradients:</strong> Adam is well-suited for sparse gradients, which is common in tasks like natural language processing. It maintains a separate adaptive learning rate for each parameter, making it less sensitive to the scale of the gradients.</p><p><strong>Combining Momentum and RMSprop:</strong> Adam combines the momentum term to accelerate convergence in the parameter space with the RMSprop term to adaptively scale the learning rates. This combination helps handle noisy gradients and navigate through saddle points efficiently.</p><p><strong>Effective in a Wide Range of Applications: </strong>Adam has shown effectiveness in a wide range of deep learning applications and is widely used in practice due to its robust performance and ease of use.</p><p><strong>Algorithm</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*2KfQsaUWKr2CyFKGUo91YA.png" /><figcaption>Adam algorithm. source: <a href="https://link.springer.com/article/10.1007/s00521-023-08568-z">springer</a></figcaption></figure><p><strong>Explaination of Adam parameters:</strong></p><p><strong>First Moment Estimate (<em>mt</em>​):</strong> This moving average is similar to the momentum term and represents the exponentially decaying average of past gradients. It helps the optimizer continue moving in the right direction even if the gradient updates become noisy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Az-RaQmiG6IGs9tpb_NSoA.png" /></figure><p><strong>Second Moment Estimate (<em>vt</em>​): </strong>This moving average is similar to the squared gradients used in RMSprop. It represents the exponentially decaying average of the past squared gradients and helps adapt the learning rates for each parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*S0R7mZTMSRDb1448BdB9kw.png" /></figure><p>The updated parameter (<em>θt</em>+1​) is then calculated using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*p9mOj_DASLGlV8gzAEfnrg.png" /></figure><ul><li><em>α</em> is the learning rate.</li><li><em>ϵ</em> is a small constant to prevent division by zero.</li><li><em>t</em> is the iteration step.</li><li><em>Jt</em>​ is the gradient of the loss function with respect to the parameters at iteration <em>t</em>.</li></ul><p>Let’s see how to code:</p><pre>import numpy as np<br><br>def adam(X, y, theta, learning_rate, iterations, beta1=0.9, beta2=0.999, epsilon=1e-8):<br>    m = len(y)<br>    m_t = np.zeros(theta.shape)<br>    v_t = np.zeros(theta.shape)<br>    t = 0<br>    <br>    for _ in range(iterations):<br>        for i in range(m):<br>            t += 1<br>            X_i = X[i, :].reshape(1, -1)<br>            y_i = y[i]<br>            prediction = np.dot(X_i, theta)<br>            error = prediction - y_i<br>            gradient = X_i.T * error<br>            <br>            m_t = beta1 * m_t + (1 - beta1) * gradient<br>            v_t = beta2 * v_t + (1 - beta2) * (gradient**2)<br>            <br>            m_t_hat = m_t / (1 - beta1**t)<br>            v_t_hat = v_t / (1 - beta2**t)<br>            <br>            theta = theta - learning_rate * m_t_hat / (np.sqrt(v_t_hat) + epsilon)<br>    <br>    return theta</pre><p>In summary, Adam combines the advantages of momentum and RMSprop to provide an adaptive and efficient optimization algorithm. It has become a popular choice for training deep neural networks due to its robust performance and ease of use.</p><p><strong>Run</strong> this <strong>main function</strong> to compare the synthetic data to several optimizers. Furthermore, remember to tune hyperparameters and use real-world datasets.</p><pre>import numpy as np<br><br>def mean_squared_error(y_true, y_pred):<br>    return np.mean((y_true - y_pred)**2)<br><br># Generate synthetic data<br>np.random.seed(40)<br>X = 2 * np.random.rand(100, 1)<br>y = 4 + 3 * X + np.random.randn(100, 1)<br><br># Add bias term to X<br>X_b = np.c_[np.ones((100, 1)), X]<br><br># Initial parameters<br>theta_initial = np.random.randn(2, 1)<br><br># Set hyperparameters<br>learning_rate = 0.003<br>iterations = 1000<br>batch_size = 32<br><br># Apply optimization algorithms<br>theta_gd = gradient_descent(X_b, y, theta_initial, learning_rate, iterations)<br>theta_sgd = stochastic_gradient_descent(X_b, y, theta_initial, learning_rate, iterations)<br>theta_rmsprop = RmsProp(X_b, y, theta_initial, learning_rate, beta=.9, iterations, epsilon=1e-7)<br>theta_adam = adam(X_b, y, theta_initial, learning_rate, iterations)<br><br># Evaluate the models<br>predictions_gd = np.dot(X_b, theta_gd)<br>predictions_sgd = np.dot(X_b, theta_sgd)<br>predictions_rmsprop = np.dot(X_b, theta_rmsprop)<br>predictions_adam = np.dot(X_b, theta_adam)<br><br># Print Mean Squared Error for each model<br>print(&quot;Mean Squared Error (Gradient Descent):&quot;, mean_squared_error(y, predictions_gd))<br>print(&quot;Mean Squared Error (Stochastic Gradient Descent):&quot;, mean_squared_error(y, predictions_sgd))<br>print(&quot;Mean Squared Error (RmsProp):&quot;, mean_squared_error(y, predictions_rmsprop))<br>print(&quot;Mean Squared Error (Adam):&quot;, mean_squared_error(y, predictions_adam))</pre><p>Thank You!</p><p>Feel free to visit my other articles..</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/unfolding-the-intelligence-machine-learning-vs-deep-learning-d8165fb70f0b">Unfolding the Intelligence: Machine Learning vs. Deep Learning</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li><li><a href="https://medium.com/@koushikkushal95/what-class-imbalance-is-all-about-details-with-examples-46d5d9da17b8">What Class Imbalance is all about: details with examples</a></li></ul><p>References</p><ul><li><a href="https://community.ibm.com/community/user/ai-datascience/blogs/pavan-saish-naru/2023/01/27/optimization-hyperparameters">Understanding Activations &amp; Optimization- Neural Networks</a></li><li><a href="https://mitpress.mit.edu/9780262537766/optimization-for-machine-learning/">Optimization for Machine Learning</a></li><li><a href="https://d2l.ai/chapter_optimization/optimization-intro.html#optimization-challenges-in-deep-learning">12.1. Optimization and Deep Learning - Dive into Deep Learning 1.0.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db1df7a2f59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Convolutional Neural Networks (CNNs) in Depth]]></title>
            <link>https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d18e299bb438</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 13:06:25 GMT</pubDate>
            <atom:updated>2023-11-28T13:06:25.204Z</atom:updated>
            <content:encoded><![CDATA[<p>Convolutional Neural Networks skillfully capturing and extracting patterns from data, revealing the hidden artistry within pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTJY9zmAF43G7wPcLrjUTw.png" /><figcaption>A simple classification architecture of Conv-Net</figcaption></figure><h3><strong>Introduction:</strong></h3><p>Convolutional Neural Networks (CNNs) have revolutionized the field of computer vision, becoming the cornerstone of image and video analysis applications. In this article, we will delve into the key components and operations that make CNNs powerful, exploring concepts like convolution, max-pooling, stride length, padding, upsampling, downsampling and more. Additionally, we’ll discuss a simple CNN model on a dataset using Python and a popular deep learning framework.</p><p>Convolutional Neural Networks (CNNs) consist of various types of layers that work together to learn hierarchical representations from input data. Each layer plays a unique role in the overall architecture. Let’s explore the key types of layers found in a typical CNN:</p><ol><li><strong>Input Layer:</strong> The input layer is the initial data entry point for the network. In image-based tasks, the input layer represents the pixel values of the image. In the following example, let’s assume we’re working with grayscale images of size 28x28 pixels.</li></ol><pre>from tensorflow.keras.layers import Input<br><br>input_layer = Input(shape=(28, 28, 1))</pre><p>2. <strong>Convolutional Layer:</strong> Convolutional layers are the core building blocks of CNNs. These layers apply convolution operations to the input data using learnable filters. These filters scan the input, extracting features such as edges, textures, and patterns</p><pre>from tensorflow.keras.layers import Conv2D<br><br>conv_layer = Conv2D(filters=32, kernel_size=(3, 3),<br>                    activation=&#39;relu&#39;)(input_layer)</pre><p>In the context of Convolutional Neural Networks (CNNs), the terms “kernel” and “filter” are often used interchangeably and refer to the same concept. Let’s break down what these terms mean:</p><p>2.1<strong> Kernel:</strong> A kernel is a small matrix used in the convolution operation. It’s a set of learnable weights that are applied to the input data to produce the output feature map. Kernels are the key elements that allow CNNs to automatically learn spatial hierarchies of features within the input data. In image processing, a kernel might be a small matrix like 3x3 or 5x5.</p><p>2.2 <strong>Filter:</strong> A filter, on the other hand, is a set of multiple kernels. In most cases, a convolutional layer uses multiple filters to capture different features in the input data. Each filter is convolved with the input to produce a feature map, and the network learns to extract various patterns by adjusting the weights (parameters) of these filters during training.</p><p>In this example, we’re defining a convolutional layer with 32 filters, each having a 3x3 kernel size. During training, the neural network adjusts the weights (parameters) of these 32 filters to learn different features from the input data. Lets see it wit an image example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9eK4kYZxLJanZwJyQuBFw.png" /><figcaption>Convolution mechanism.Kernel shape(3X3). imagesource:opengenus</figcaption></figure><p>In summary, the kernel is the small matrix that slides or convolves across the input data, and the filter is a set of these kernels used to extract various features from the input, allowing the neural network to learn hierarchical representations.</p><p>3. <strong>Activation Layer (ReLU)</strong>: After the convolution operation, an activation function, often Rectified Linear Unit (ReLU), is applied element-wise to introduce non-linearity into the model. ReLU helps the network learn complex relationships and makes the model more expressive. It completely depends upon your use case which activation you will use, in most cases researchers use ReLU, there some activations which can also be used, for example: Leaky ReLU, ELU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_aXeZKGgpYQvakMvNxrLDA.png" /><figcaption>ReLU activation. source: <a href="https://www.researchgate.net/figure/Commonly-used-activation-functions-a-Sigmoid-b-Tanh-c-ReLU-and-d-LReLU_fig3_335845675">researchgate</a></figcaption></figure><p>Implementing the Rectified Linear Unit (ReLU) function in Python is quite straightforward. ReLU is an activation function commonly used in neural networks to <strong>introduce non-linearity</strong>. Here’s a simple Python implementation:</p><pre>def relu(x):<br>    return max(0, x)</pre><p>4. <strong>Pooling Layer</strong>: Pooling layers (e.g., <strong>MaxPooling</strong> or <strong>AveragePooling</strong>) reduce the spatial dimensions of the feature maps generated by the convolutional layers. MaxPooling, for instance, selects the maximum value from a group of values, focusing on the most salient features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*k5wxI8SOJzAfGonAopncqA.png" /><figcaption>Max Pooling — Average Pooling. source: <a href="https://www.researchgate.net/figure/Illustration-of-Max-Pooling-and-Average-Pooling-Figure-2-above-shows-an-example-of-max_fig2_333593451">researchgate</a></figcaption></figure><p>Pooling layers reduce spatial dimensions. MaxPooling is commonly used:</p><pre>from tensorflow.keras.layers import MaxPooling2D<br><br>pooling_layer = MaxPooling2D(pool_size=(2, 2))(conv_layer)</pre><p>5. <strong>Fully Connected (Dense) Layer</strong>: Fully Connected layers connect every neuron in <strong>one layer to every neuron</strong> in the <strong>next layer</strong>. These layers are typically found towards the end of the network, transforming the learned features into predictions or class probabilities.Fully connected layers are <strong>typically used towards the end of the network</strong>. For classification tasks:</p><pre>from tensorflow.keras.layers import Dense, Flatten<br><br>flatten_layer = Flatten()(pooling_layer)<br>dense_layer = Dense(units=128, activation=&#39;relu&#39;)(flatten_layer)</pre><p>6.<strong> Dropout Layer</strong>: Dropout layers are used for <strong>regularization</strong> to <a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b"><strong>prevent overfitting</strong></a>. During training, random neurons are “dropped out,” meaning they are ignored, forcing the network to learn more robust and generalized features. It help prevent overfitting by randomly ignoring a fraction of input units during training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*qM6ZRfezI6mVLz7B9X0LvA.gif" /><figcaption>Dropout mechanism. source <a href="https://nagadakos.github.io/2018/09/23/dropout-effect-discussion/">nagadakos</a></figcaption></figure><pre>from tensorflow.keras.layers import Dropout<br><br>dropout_layer = Dropout(rate=0.5)(dense_layer)</pre><p>7. <strong>Batch Normalization Layer</strong>: Batch Normalization (BN) is a technique used in neural networks to stabilize and accelerate the training process. It normalizes the inputs of a layer by adjusting and scaling them during training. The mathematical details behind Batch Normalization involve normalization, scaling, and shifting operations. Let’s delve into the mathematics of Batch Normalization.</p><p>Suppose we have a mini-batch of size <em>m</em> with <em>n</em> features. The input to the Batch Normalization can be summarized as follows:</p><p>7.1. <strong>Mean Calculation</strong>: Calculate the mean <em>μ</em> of the mini-batch for each feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*pa2d5KHbAaDXZ2faxtnUCQ.png" /><figcaption>Mean of array X</figcaption></figure><p>Here, <em>xi</em>​ represents the values of the <em>i</em>-th feature across the mini-batch.</p><p>7.2. <strong>Variance Calculation</strong>: Calculate the variance <em>σ²</em> of the mini-batch for each feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*1G7poAdh6ogo24fbtLzMGA.png" /><figcaption>Variance calculation</figcaption></figure><p>7.3. <strong>Normalize</strong>: Normalize the input by subtracting the mean and dividing by the standard deviation (<em>σ</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*CQRbCkO2AeqCnvP_d4J-dA.png" /><figcaption>Normalize in range</figcaption></figure><p>Here, <em>ϵ</em> is a small constant added to avoid division by zero.</p><p>7.4. <strong>Scale and Shift</strong>: Introduce learnable parameters (<em>γ</em> and <em>β</em>) to scale and shift the normalized values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*q7QN-59PIZo70kNKebpSsQ.png" /><figcaption>Scaling of each batch</figcaption></figure><p>Here, <em>γ</em> is the scale parameter, and <em>β</em> is the shift parameter.</p><p>The Batch Normalization operation is typically inserted before the activation function in a neural network layer. It has been shown to have regularization effects and can mitigate issues like internal covariate shift, making training more stable and faster. Here is a simple code, for batch normalization in CNN or any deep neural network.</p><pre>from tensorflow.keras.layers import BatchNormalization<br><br>batch_norm_layer = BatchNormalization()(dropout_layer)</pre><p>In summary, Batch Normalization normalizes the input, scales and shifts the normalized values, and introduces learnable parameters to allow the network to adapt during training. The use of Batch Normalization has become a standard practice in deep learning architectures.</p><p>8. <strong>Flatten Layer</strong>: Flatten layers convert multi-dimensional feature maps into a one-dimensional vector, preparing the data for input into fully connected layers.</p><pre>flatten_layer = Flatten()(batch_norm_layer)</pre><p>9. <strong>Upsampling Layer</strong>: Upsampling is a technique used in deep learning to increase the spatial resolution of feature maps. It is often employed in tasks like image segmentation and generation. Here are brief descriptions of common types of upsampling methods:</p><p>9.1. <strong>Nearest Neighbors (NN) Upsampling</strong>: Nearest Neighbors (NN) upsampling, also known as upsampling by duplication or replication, is a simple and intuitive method. In this approach, each pixel in the input is duplicated or replicated to generate a larger output. While straightforward, NN upsampling may lead to blocky artifacts and a loss of fine details since it does not interpolate between neighboring pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*-z5guEKuL_JdZ7b0dm10dg.png" /><figcaption>Nearest Neighbor Upsampling.</figcaption></figure><p>9.2. <strong>Transposed Convolution (Deconvolution) Upsampling</strong>: Transposed Convolution, often referred to as deconvolution, is a learnable upsampling method. It involves using a convolutional operation with learnable parameters to increase the spatial dimensions of the input. The weights in the transposed convolutional layer are trained during the optimization process, allowing the network to learn upsampling patterns specific to the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV21UOHCZjnwIWO0dARiyg.jpeg" /></figure><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Conv2DTranspose<br><br># Transposed Convolution Upsampling<br>transposed_conv_upsampling = Conv2DTranspose(filters=32, kernel_size=(3, 3), strides=(2, 2), padding=&#39;same&#39;)</pre><p>Each upsampling method has its advantages and trade-offs, and the choice depends on the specific requirements of the task and the characteristics of the data.</p><h3><strong>Padding and stride</strong></h3><p>These are crucial concepts in convolutional neural networks (CNNs) that influence the size of the output feature maps after convolution operations. Let’s discuss three types of padding and also explain the concept of stride.</p><p><strong>Valid Padding (No Padding)</strong>: In valid padding, also known as no padding, there is no additional padding added to the input before applying the convolution operation. As a result, the convolution operation is only performed where the filter and the input fully overlap. This often leads to a reduction in the spatial dimensions of the output feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*RHtc-K3HEzhWU5JZ3ymQvA.jpeg" /></figure><pre>from tensorflow.keras.layers import Conv2D<br><br># Valid Padding<br>valid_padding_conv = Conv2D(filters=32, kernel_size=(3, 3),<br>                             strides=(1, 1), padding=&#39;valid&#39;)</pre><p><strong>Same Padding</strong>: Same padding ensures that the output feature map has the same spatial dimensions as the input. It achieves this by adding zero-padding to the input such that the filter can slide over the input without going outside its boundaries. The amount of padding is calculated to keep the dimensions the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*noYcUAa_P8nRilg3Lt_nuA.png" /></figure><pre>from tensorflow.keras.layers import Conv2D<br><br>#Padding in Keras<br>same_padding_conv = Conv2D(filters=32, kernel_size=(3, 3), <br>                          strides=(1, 1), padding=&#39;same&#39;)</pre><p><strong>Stride</strong>: Stride defines the step size at which the filter moves across the input during convolution. A larger stride results in a reduction of the spatial dimensions of the output feature map. Stride can be adjusted to control the level of downsampling in the network.</p><pre>from tensorflow.keras.layers import Conv2D<br><br># Example of Convolution with Stride in Keras<br>conv_with_stride = Conv2D(filters=32, kernel_size=(3, 3), <br>                                  strides=(2, 2), padding=&#39;same&#39;)</pre><p>In this example, the stride is set to (2, 2), indicating that the filter moves two pixels at a time in both the horizontal and vertical directions. Stride is a critical parameter for controlling the spatial resolution of the feature maps and influencing the receptive field of the network.</p><p>In this article, I would like to explore building a simple, Convolutional Neural Network from scratch. Let’s do the most popular classification task of early computer vision task for learning : <strong>Cats vs. Dogs classification.</strong></p><p>This task comprises with a few steps to follow:</p><h3>Import Libraries:</h3><pre>import tensorflow_datasets as tfds<br>import tensorflow as tf<br>from tensorflow.keras import layers<br><br>import keras<br>from keras.models import Sequential,Model<br>from keras.layers import Dense,Conv2D,Flatten,MaxPooling2D,GlobalAveragePooling2D<br>from keras.utils import plot_model<br><br>import numpy as np<br>import matplotlib.pyplot as plt<br>import scipy as sp<br>import cv2</pre><h3>Load data: the Cats vs Dogs dataset</h3><pre>!curl -O https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_5340.zip<br>!unzip -q kagglecatsanddogs_5340.zip<br>!ls</pre><p>The cell below will preprocess the images and create batches before feeding it to our model.</p><pre>def augment_images(image, label):<br>  <br>  # cast to float<br>  image = tf.cast(image, tf.float32)<br>  # normalize the pixel values<br>  image = (image/255)<br>  # resize to 300 x 300<br>  image = tf.image.resize(image,(300,300))<br><br>  return image, label<br><br># use the utility function above to preprocess the images<br>augmented_training_data = train_data.map(augment_images)<br><br># shuffle and create batches before training<br>train_batches = augmented_training_data.shuffle(1024).batch(32)</pre><h3>Filter out corrupted images</h3><p>When working with lots of real-world image data, corrupted images are a common occurence. Let’s filter out badly-encoded images that do not feature the string “JFIF” in their header.</p><pre>import os<br><br>num_skipped = 0<br>for folder_name in (&quot;Cat&quot;, &quot;Dog&quot;):<br>    folder_path = os.path.join(&quot;PetImages&quot;, folder_name)<br>    for fname in os.listdir(folder_path):<br>        fpath = os.path.join(folder_path, fname)<br>        try:<br>            fobj = open(fpath, &quot;rb&quot;)<br>            is_jfif = tf.compat.as_bytes(&quot;JFIF&quot;) in fobj.peek(10)<br>        finally:<br>            fobj.close()<br><br>        if not is_jfif:<br>            num_skipped += 1<br>            # Delete corrupted image<br>            os.remove(fpath)<br><br>print(&quot;Deleted %d images&quot; % num_skipped)</pre><h3>Generate a Dataset</h3><pre>image_size = (300, 300)<br>batch_size = 128<br><br>train_ds, val_ds = tf.keras.utils.image_dataset_from_directory(<br>    &quot;PetImages&quot;,<br>    validation_split=0.2,<br>    subset=&quot;both&quot;,<br>    seed=1337,<br>    image_size=image_size,<br>    batch_size=batch_size,<br>)</pre><h3>Visualize the data</h3><p>Here are the first 9 images in the training dataset. As you can see, label 1 is “dog” and label 0 is “cat”.</p><pre>import matplotlib.pyplot as plt<br><br>plt.figure(figsize=(6, 6))<br>for images, labels in train_ds.take(1):<br>    for i in range(9):<br>        ax = plt.subplot(3, 3, i + 1)<br>        plt.imshow(images[i].numpy().astype(&quot;uint8&quot;))<br>        plt.title(int(labels[i]))<br>        plt.axis(&quot;off&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Lnxwj2-sb9reStbGa9_4JA.png" /><figcaption>Annotated Dataset. Dog: 1 , Cat:0</figcaption></figure><h3>Using image data augmentation</h3><p>When you don’t have a large image dataset, it’s a good practice to artificially introduce sample diversity by applying random yet realistic transformations to the training images, such as random horizontal flipping or small random rotations. This helps expose the model to different aspects of the training data while slowing down overfitting.</p><pre>data_augmentation = keras.Sequential(<br>    [<br>        layers.RandomFlip(&quot;horizontal&quot;),<br>        layers.RandomRotation(0.1),<br>    ]<br>)</pre><p>Let’s visualize what the augmented samples look like, by applying data_augmentation repeatedly to the first image in the dataset:</p><pre>plt.figure(figsize=(6, 6))<br>for images, _ in train_ds.take(1):<br>    for i in range(9):<br>        augmented_images = data_augmentation(images)<br>        ax = plt.subplot(3, 3, i + 1)<br>        plt.imshow(augmented_images[0].numpy().astype(&quot;uint8&quot;))<br>        plt.axis(&quot;off&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*YfqgFZXt4vt5Z0qzxmmJcg.png" /><figcaption>Image augmentation. (Ex: Flip, Rotation)</figcaption></figure><h3>Configure the dataset for performance</h3><p>Let’s apply data augmentation to our training dataset, and let’s make sure to use buffered prefetching so we can yield data from disk without having I/O becoming blocking:</p><pre># Apply `data_augmentation` to the training images.<br>train_ds = train_ds.map(<br>    lambda img, label: (data_augmentation(img), label),<br>    num_parallel_calls=tf.data.AUTOTUNE,<br>)<br># Prefetching samples in GPU memory helps maximize GPU utilization.<br>train_ds = train_ds.prefetch(tf.data.AUTOTUNE)<br>val_ds = val_ds.prefetch(tf.data.AUTOTUNE)</pre><h3>Build the classifier</h3><p>This will look familiar to you because it is almost identical to the previous model we built. The key difference is the output is just one unit that is sigmoid activated. This is because we’re only dealing with two classes.</p><pre><br>class CustomModel(Sequential):<br>    def __init__(self):<br>        super(CustomModel, self).__init__()<br><br>        self.add(Conv2D(16, input_shape=(300, 300, 3), kernel_size=(3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>        self.add(MaxPooling2D(pool_size=(2, 2)))<br><br>        self.add(Conv2D(32, kernel_size=(3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>        self.add(MaxPooling2D(pool_size=(2, 2)))<br><br>        self.add(Conv2D(64, kernel_size=(3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>        self.add(MaxPooling2D(pool_size=(2, 2)))<br><br>        self.add(Conv2D(128, kernel_size=(3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>        self.add(GlobalAveragePooling2D())<br>        self.add(Dense(1, activation=&#39;sigmoid&#39;))<br><br># Instantiate the custom model<br>model = CustomModel()<br><br># Display the model summarymodel.summary()</pre><p>The loss can be adjusted from last time to deal with just two classes. For that, we pick binary_crossentropy.</p><pre># Training will take around 30 minutes to complete using a GPU. <br># If you haven&#39;t GPU in your local machine, feel free to use <br># Google colabaratory to get GPU access.<br><br>model.compile(loss=&#39;binary_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;],<br>              optimizer=tf.keras.optimizers.RMSprop(lr=0.001))<br>model.fit(train_ds,<br>          epochs=25,<br>          validation_data=val_ds,)</pre><h3>Testing the Model</h3><p>Let’s download a few images and see how the class activation maps look like.</p><pre>!wget -O cat1.jpg https://storage.googleapis.com/laurencemoroney-blog.appspot.com/MLColabImages/cat1.jpg<br>!wget -O cat2.jpg https://storage.googleapis.com/laurencemoroney-blog.appspot.com/MLColabImages/cat2.jpg<br>!wget -O catanddog.jpg https://storage.googleapis.com/laurencemoroney-blog.appspot.com/MLColabImages/catanddog.jpg<br>!wget -O dog1.jpg https://storage.googleapis.com/laurencemoroney-blog.appspot.com/MLColabImages/dog1.jpg<br>!wget -O dog2.jpg https://storage.googleapis.com/laurencemoroney-blog.appspot.com/MLColabImages/dog2.jpg</pre><pre># utility function to preprocess an image and show the CAM<br>def convert_and_classify(image):<br><br>  # load the image<br>  img = cv2.imread(image)<br><br>  # preprocess the image before feeding it to the model<br>  img = cv2.resize(img, (300,300)) / 255.0<br><br>  # add a batch dimension because the model expects it<br>  tensor_image = np.expand_dims(img, axis=0)<br><br>  # get the features and prediction<br>  features,results = cam_model.predict(tensor_image)<br>  <br>  # generate the CAM<br>  show_cam(tensor_image, features, results)<br><br>convert_and_classify(&#39;cat1.jpg&#39;)<br>convert_and_classify(&#39;cat2.jpg&#39;)<br>convert_and_classify(&#39;catanddog.jpg&#39;)<br>convert_and_classify(&#39;dog1.jpg&#39;)<br>convert_and_classify(&#39;dog2.jpg&#39;)</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou4OTDK712IPxr4lai_OkQ.png" /><figcaption>Predicted output of classification model.</figcaption></figure><p>Thank you!</p><p>I wanted to take a moment to express my sincere gratitude for taking the time to read my article. Your engagement and interest mean a lot to me.</p><p>Feel free to get the web app based on this classification <a href="https://huggingface.co/spaces/Koushikl0l/catsVsdogs">here</a>.</p><p>Find out my other articles:</p><ul><li><a href="https://medium.com/@koushikkushal95/building-the-foundation-calculus-math-and-linear-algebra-for-machine-learning-91a95e2f36b7">Building the Foundation: Calculus, Math and Linear Algebra for Machine Learning</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li><li><a href="https://medium.com/@koushikkushal95/unfolding-the-intelligence-machine-learning-vs-deep-learning-d8165fb70f0b">Unfolding the Intelligence: Machine Learning vs. Deep Learning</a></li><li><a href="https://medium.com/@koushikkushal95/mnist-hand-written-digit-classification-using-neural-network-from-scratch-54da85712a06">MNIST(hand written digit) Classification Using Neural Network From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/logistic-regression-from-scratch-dfb8527a4226">Logistic Regression From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/what-class-imbalance-is-all-about-details-with-examples-46d5d9da17b8">What Class Imbalance is all about: details with examples</a></li></ul><p>References:</p><ul><li><a href="https://www.coursera.org/learn/advanced-computer-vision-with-tensorflow">Advanced Computer Vision with TensorFlow</a></li><li><a href="https://cs231n.github.io/">CS231n Deep Learning for Computer Vision</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d18e299bb438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Foundation: Calculus, Math and Linear Algebra for Machine Learning]]></title>
            <link>https://medium.com/@koushikkushal95/building-the-foundation-calculus-math-and-linear-algebra-for-machine-learning-91a95e2f36b7?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91a95e2f36b7</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 19:49:59 GMT</pubDate>
            <atom:updated>2023-11-27T19:49:59.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*C8ligvoqqRjGdkEzoi4Rkw.jpeg" /></figure><p>Machine learning is a fascinating field that empowers computers to learn from data and make predictions or decisions without being explicitly programmed. Behind the scenes, however, there’s a robust foundation of mathematics and linear algebra that forms the backbone of machine learning algorithms. In this article, we’ll explore the key mathematical concepts and linear algebra fundamentals you should be familiar with before delving into machine learning.</p><h3>The Mathematics of Machine Learning:</h3><h3>1. Calculus:</h3><p>Calculus plays a crucial role in understanding the optimization algorithms that are fundamental to machine learning. Gradient descent, a widely used optimization algorithm, relies on the derivatives of a function. Let’s take a simple example:</p><p><em>f</em>(<em>x</em>) = <em>x</em>²</p><p>To find the derivative <em>f</em>′(<em>x</em>), we can use Python:</p><pre>import sympy as sp<br><br>x = sp.symbols(&#39;x&#39;)<br>f = x**2<br>derivative = sp.diff(f, x)<br>print(&quot;Derivative of f(x) =&quot;, derivative)</pre><p>This will output the derivative <em>f</em>′(<em>x</em>)=2<em>x</em>. Calculus helps us understand how a function changes and guides the optimization process in machine learning.</p><h3>2. Probability and Statistics:</h3><p>Probability and statistics are the backbone of machine learning, particularly in understanding uncertainty, distributions, and making informed decisions based on data. For instance, the probability density function of a normal distribution:</p><p>Python allows us to work with probability distributions using libraries such as NumPy and SciPy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*LMKJAjFddZZADhBU-nU3MQ.png" /><figcaption>probability density function</figcaption></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import norm<br><br>mu, sigma = 0, 1<br>x = np.linspace(-5, 5, 1000)<br>plt.plot(x, norm.pdf(x, mu, sigma))<br>plt.title(&#39;Normal Distribution&#39;)<br>plt.show()</pre><h3>Linear Algebra in Machine Learning:</h3><p>Linear algebra is the language of machine learning, providing the tools to understand and manipulate the data efficiently.</p><h3>1. Vectors and Matrices:</h3><p>Vectors and matrices are the building blocks of linear algebra. A vector can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*EdYr9UcyIENiv8qXms3C8Q.png" /></figure><p>And a matrix as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*UCCPlMgRS4_ULf0c5BAKIQ.png" /></figure><h3>2. Matrix Multiplication:</h3><p>Matrix multiplication is a fundamental operation in machine learning. Given two matrices A and B, the product C = A ⋅ B is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*hfUsKeGPdWSdGUf_sWF1JQ.png" /><figcaption>matrix multiplication</figcaption></figure><p>Let’s implement this in Python:</p><pre>import numpy as np<br><br>A = np.array([[1, 2], [3, 4]])<br>B = np.array([[5, 6], [7, 8]])<br><br>C = np.dot(A, B)<br>print(&quot;Matrix Multiplication Result:&quot;)<br>print(C)</pre><h3>3. Eigendecomposition:</h3><p>Eigendecomposition is another crucial concept. Given a square matrix A, it can be decomposed into its eigenvalues (<em>λ</em>) and eigenvectors (v):</p><p>Av= λv</p><p>This is often employed in dimensionality reduction techniques like Principal Component Analysis (PCA).</p><h3>Derivatives and Gradient Descent:</h3><p>We discussed finding derivatives earlier, and now let’s use the derivative in the context of gradient descent. Gradient descent is an optimization algorithm used to minimize a function iteratively. For example:</p><p><em>f</em>(<em>x</em>) = <em>x³</em>− 3<em>x² </em>+ 2<em>x </em>+ 1</p><p>We can find the minimum by iteratively updating <em>x</em> using the gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*pzUgqogsdEAmvkaSvlg5OA.png" /><figcaption>subtracting gradient</figcaption></figure><p>where <em>α</em> is the learning rate. Let’s implement this in Python:</p><pre>import sympy as sp<br><br>x = sp.symbols(&#39;x&#39;)<br>f = x**3 - 3*x**2 + 2*x + 1<br>derivative = sp.diff(f, x)<br><br># Gradient Descent<br>alpha = 0.1<br>x_val = 2  # Initial value of x<br>iterations = 10<br><br>for _ in range(iterations):<br>    x_val = x_val - alpha * derivative.subs(x, x_val)<br><br>print(&quot;Minimum value of f(x) at x =&quot;, x_val)</pre><h3>1. Integration:</h3><p>Integration is another fundamental concept, particularly in areas such as probability where integrating a probability density function gives the cumulative distribution function. Let’s integrate a simple function:</p><p>∫( 3<em>x²</em>+ 2<em>x </em>)<em>dx</em></p><pre>integral_result = sp.integrate(3*x**2 + 2*x, x)<br>print(&quot;Integral result =&quot;, integral_result)</pre><h3>2. Solving Equations:</h3><p>Solving equations is a common task, especially in linear algebra and optimization. Let’s solve a simple equation:</p><p>2x+5=0</p><pre>solution = sp.solve(2*x + 5, x)<br>print(&quot;Solution for 2x + 5 =&quot;, solution)</pre><h3>3. Matrix Inversion:</h3><p>Matrix inversion is crucial for solving linear systems of equations. Given a matrix A and its inverse <strong>A</strong>−, the product should be the identity matrix <strong>I</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*-U0fJVJnXH67AXcV23o1Uw.png" /></figure><p>Let’s demonstrate this in Python:</p><pre>A = np.array([[2, 1], [1, 3]])<br>A_inv = np.linalg.inv(A)<br>identity_matrix = np.dot(A, A_inv)<br><br>print(&quot;Original Matrix A:&quot;)<br>print(A)<br>print(&quot;\nInverse of A:&quot;)<br>print(A_inv)<br>print(&quot;\nProduct of A and A_inv (should be the identity matrix):&quot;)<br>print(identity_matrix)</pre><h3><strong>Conclusion:</strong></h3><p>A strong foundation in mathematics and linear algebra is essential for anyone diving into machine learning. Understanding calculus for optimization, probability and statistics for dealing with data uncertainty, and linear algebra for efficient data manipulation are keys to unlocking the full potential of machine learning algorithms. Python, with its rich ecosystem of libraries, provides a powerful platform to implement and experiment with these mathematical concepts in the context of machine learning. Happy learning!</p><p>Feel free to visit some useful articles..</p><ul><li><a href="https://medium.com/@koushikkushal95/unfolding-the-intelligence-machine-learning-vs-deep-learning-d8165fb70f0b">Unfolding the Intelligence: Machine Learning vs. Deep Learning</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li><li><a href="https://medium.com/@koushikkushal95/mnist-hand-written-digit-classification-using-neural-network-from-scratch-54da85712a06">MNIST(hand written digit) Classification Using Neural Network From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/logistic-regression-from-scratch-dfb8527a4226">Logistic Regression From Scratch</a></li></ul><p>References:</p><p><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjx1fiJ-OSCAxX93jgGHfFKCvQQFnoECBoQAQ&amp;url=https%3A%2F%2Fwww.coursera.org%2Flearn%2Flinear-algebra-machine-learning&amp;usg=AOvVaw1l_dIkm8CODarmg0-WDahn&amp;opi=89978449">Mathematics for Machine Learning: Linear AlgebraCourserahttps://www.coursera.org › … › Machine Learning</a></p><p><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwippZWt-OSCAxU--zgGHaSyCyMQFnoECDQQAQ&amp;url=https%3A%2F%2Fwww.oreilly.com%2Flibrary%2Fview%2Fessential-math-for%2F9781098102920%2F&amp;usg=AOvVaw2CTqiliU60MhDLQwA9NNsb&amp;opi=89978449">Essential Math for Data Science</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91a95e2f36b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unfolding the Intelligence: Machine Learning vs. Deep Learning]]></title>
            <link>https://medium.com/@koushikkushal95/unfolding-the-intelligence-machine-learning-vs-deep-learning-d8165fb70f0b?source=rss-1670d68f972f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8165fb70f0b</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Koushik Ahmed Kushal]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 19:05:31 GMT</pubDate>
            <atom:updated>2023-11-28T14:34:35.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdUwIWA-ta1ABrn02-TFSA.jpeg" /><figcaption>Machine Learning vs. Deep Learning</figcaption></figure><h3><strong>Introduction:</strong></h3><p>In the ever-evolving landscape of artificial intelligence, two terms that frequently emerge are “machine learning” and “deep learning.” While they are often used interchangeably, these concepts represent distinct approaches to solving problems. In this article, we’ll delve into the mathematical foundations and practical differences between machine learning and deep learning, showcasing code examples to illustrate their unique characteristics.</p><p><strong>1. Machine Learning: The Foundation of Intelligence</strong></p><p>At its core, machine learning involves the development of algorithms that enable systems to learn patterns and make decisions based on data without explicit programming. A fundamental concept in machine learning is the use of models, which are mathematical representations of relationships within the data.</p><p>Mathematically, a simple linear regression model can be expressed as:</p><p><strong><em>y</em> = <em>mx</em> + <em>b</em></strong></p><p>Here, <em>y</em> represents the output, <em>x</em> is the input, <em>m</em> is the slope, and <em>b</em> is the intercept. This basic equation showcases the essence of machine learning — learning the optimal values of <em>m</em> and <em>b</em> from the data to make accurate predictions.</p><p><strong>2. Deep Learning: Unleashing Neural Networks</strong></p><p>Deep learning, on the other hand, is a subset of machine learning that leverages neural networks, inspired by the human brain’s architecture. The mathematical backbone of deep learning is the neural network, composed of interconnected layers of nodes (neurons). Each connection between nodes has a weight, and the network learns these weights during training.</p><p>A simple neural network can be represented mathematically as:</p><p><strong><em>y</em> = <em>f </em>( <em>w</em>2⋅ <em>f </em>( <em>w</em>1⋅<em>x </em>+ <em>b</em>1 ​) + <em>b</em>2 )</strong></p><p>Here, <em>x</em> is the input, <em>w</em>1​ and <em>w</em>2​ are the weights, <em>b</em>1​ and <em>b</em>2​ are biases, and <em>f</em> is an activation function. The network learns the optimal values of <em>w</em> and <em>b</em> through a process called backpropagation, adjusting these parameters to minimize the difference between predicted and actual outcomes.</p><p><strong>3. Key Differences:</strong></p><p><strong>-Data Complexity:</strong></p><p><em>Machine Learning:</em> Suitable for structured data with well-defined features.</p><p><em>Deep Learning:</em> Excels in unstructured data like images, audio, and text, where feature extraction is complex.</p><p><strong>-Model Complexity:</strong></p><p><em>Machine Learning:</em> Relies on handcrafted features and simpler models.</p><p><em>Deep Learning:</em> Automatically learns hierarchical features through multiple layers, handling intricate patterns.</p><p><strong>-Training Scale:</strong></p><p><em>Machine Learning:</em> Requires less data and is often quicker to train.</p><p><em>Deep Learning:</em> Thrives on vast datasets, benefiting from the ability to capture intricate relationships.</p><p><strong>4. Code Examples:</strong></p><p><em>Machine Learning (Linear Regression in Python):</em></p><pre>from sklearn.linear_model import LinearRegression<br>model = LinearRegression()<br>model.fit(X_train, y_train)<br>predictions = model.predict(X_test)</pre><p><em>Deep Learning (Neural Network in TensorFlow):</em></p><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Dense<br>from tensorflow.keras import Model<br><br># Define a custom neural network class using subclassing<br>class SimpleNeuralNetwork(Model):<br>    def __init__(self):<br>        super(SimpleNeuralNetwork, self).__init__()<br>        self.layer1 = Dense(64, activation=&#39;relu&#39;)<br>        self.layer2 = Dense(1)<br><br>    def call(self, inputs):<br>        x = self.layer1(inputs)<br>        return self.layer2(x)<br><br># Create an instance of the model<br>model = SimpleNeuralNetwork()<br><br># Compile the model<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)<br><br># Generate some dummy data for training<br>import numpy as np<br>X_train = np.random.rand(100, 10)<br>y_train = np.random.rand(100, 1)<br><br># Train the model<br>model.fit(X_train, y_train, epochs=10, batch_size=32)<br><br># Generate predictions<br>X_test = np.random.rand(10, 10)<br>predictions = model.predict(X_test)<br>print(predictions)</pre><p>In this example, we create a custom neural network class SimpleNeuralNetwork that subclasses tf.keras.Model. Inside the class, we define the layers of our neural network in the __init__ method and the forward pass in the call method. This provides a flexible and intuitive way to create deep learning models.</p><p>The model.compile function sets the optimizer and loss function, and then the model is trained using the fit method with dummy data. Finally, we use the trained model to make predictions on a test dataset.</p><p>This subclassing approach allows for more fine-grained control over the architecture of the neural network, making it suitable for designing complex models for various tasks.</p><p><strong>Conclusion:</strong></p><p>In conclusion, machine learning and deep learning represent two facets of artificial intelligence, each with its own mathematical underpinnings and areas of applicability. While machine learning is versatile and suitable for various tasks, deep learning shines in handling complex, unstructured data. Understanding these differences is crucial for practitioners navigating the diverse landscape of artificial intelligence. As technology advances, both machine learning and deep learning will continue to shape the future of intelligent systems.</p><p>Feel free to visit other articles..</p><ul><li><a href="https://medium.com/@koushikkushal95/understanding-convolutional-neural-networks-cnns-in-depth-d18e299bb438">Understanding Convolutional Neural Networks (CNNs) in Depth</a></li><li><a href="https://medium.com/@koushikkushal95/logistic-regression-from-scratch-dfb8527a4226">Logistic Regression From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/mnist-hand-written-digit-classification-using-neural-network-from-scratch-54da85712a06">MNIST(hand written digit) Classification Using Neural Network From Scratch</a></li><li><a href="https://medium.com/@koushikkushal95/what-is-overfitting-and-underfitting-and-how-to-deal-with-it-step-by-step-d6c335ed086b">What is Overfitting and Underfitting , and how to deal with it step by step?</a></li></ul><p>References</p><ul><li><a href="https://www.coursera.org/articles/ai-vs-deep-learning-vs-machine-learning-beginners-guide#">Deep Learning vs. Machine Learning: A Beginner&#39;s Guide</a></li><li><a href="https://www.ibm.com/blog/ai-vs-machine-learning-vs-deep-learning-vs-neural-networks/">AI vs. Machine Learning vs. Deep Learning vs. Neural Networks: What&#39;s the difference?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8165fb70f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>