<?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 Akash Nath on Medium]]></title>
        <description><![CDATA[Stories by Akash Nath on Medium]]></description>
        <link>https://medium.com/@akashnath29?source=rss-9941da589fa0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CkR0VB-7wM8uvjNpkVsCRw.jpeg</url>
            <title>Stories by Akash Nath on Medium</title>
            <link>https://medium.com/@akashnath29?source=rss-9941da589fa0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:20:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akashnath29/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[Perplexity’s $34.5B Chrome Bid: Genius Move or Billion-Dollar Bluff?]]></title>
            <link>https://akashnath29.medium.com/perplexitys-34-5b-chrome-bid-genius-move-or-billion-dollar-bluff-0f39fa7df528?source=rss-9941da589fa0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f39fa7df528</guid>
            <category><![CDATA[silicon-valley]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology-news]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[perplexity]]></category>
            <dc:creator><![CDATA[Akash Nath]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 00:13:16 GMT</pubDate>
            <atom:updated>2025-08-13T00:13:16.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqqO_s3ybGpKTQEQxsVePg.jpeg" /><figcaption>Perplexity Buys Chrome?</figcaption></figure><h3>Index</h3><ol><li><a href="#2fa9">Introduction — The $34.5B Shockwave</a></li><li><a href="#f0c3">A David with a King’s Ransom</a></li><li><a href="#49a8">The Legal Storm Over Mountain View</a></li><li><a href="#e83c">Comet: The Crown Prince</a></li><li><a href="#066c">Echoes of Musk</a></li><li><a href="#5a5a">Bluff, Battle, or Both?</a></li><li><a href="#90e8">The AI Browser Wars</a></li><li><a href="#ce27">Risks and Realities</a></li><li><a href="#7b08">Win or Lose, a Win</a></li><li><a href="#6701">The Opening Salvo</a></li><li><a href="#3896">Sources</a></li></ol><h3>The $34 Billion Shockwave</h3><p>On August 12, 2025, Alphabet CEO Sundar Pichai received an unexpected message in his inbox amid the quiet bustle of Mountain View’s corporate towers.<br>It wasn’t from a tech tycoon like Satya Nadella, a board member, or a regulator.</p><p>The offer to purchase Google Chrome for an astounding $34.5 billion in cash came from Perplexity AI, a six-year-old AI search startup valued at just $18 billion [1].</p><p>It sounded almost unbelievable. With 64.86% of the global browser market, Chrome is more than just another browser; it serves as the internet’s entry point for 3.45 billion people globally [2]. To put it into perspective, owning Chrome is like owning the world’s busiest port — every ship, trade route, and journey passes through your waters in some way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrA-wjJwf1jv5EJIT0LMpg.png" /><figcaption>Global Browser Market Share 2025</figcaption></figure><h3>A David with a King’s Ransom</h3><p>The offer from Perplexity was thoughtfully constructed [3]. They agreed to keep Google Search as the default search engine, promised to keep Chromium, Chrome’s open-source core, free for all users, and committed to investing an additional $3 billion in Chrome over the following two years. To guarantee a smooth transition, Chrome’s engineering team would also be encouraged to remain on board.</p><p>That in and of itself would have been audacious. However, the world was taken aback by the scope of the ambition. Perplexity was only valued at $500 million eighteen months ago. It skyrocketed to $18 billion by July 2025, a 3,600% increase [4]. Nvidia, Jeff Bezos, Yann LeCun, New Enterprise Associates, and SoftBank Vision Fund 2 are among the all-star list of backers [5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KafneE_hAd-r9pHsjSoSlA.png" /><figcaption>Perplexity Valuation Growth Timeline</figcaption></figure><h3>The Legal Storm Over Mountain View</h3><p>Before Sundar finished his morning chai five years ago, such an offer would have been laughed out of the room. However, things have changed.</p><p>Citing $26.3 billion spent on default search agreements in 2021 alone, Judge Amit Mehta declared in August 2024 that Google had unlawfully monopolised the search market [6]. By November, the DOJ was advocating for a drastic solution: requiring Google to sell off Chrome [7].</p><p>Drawing comparisons to Google’s 2012 sale of Motorola Home to Arris Group, experts testified during a remedies trial in April–May 2025 that spinning off Chrome was technically possible [8]. All of a sudden, the impossible was now feasible: Chrome might need to relocate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr9HvJjVZYOJo4Y6VpKf9g.png" /><figcaption>Antitrust Case Timeline — DOJ vs Google</figcaption></figure><h3>Comet: The Crown Prince</h3><p>In the browser game, confusion is nothing new. It quietly released Comet, an AI-native browser built on Chromium, in July 2025 [9]. Perplexity refers to Comet as a “cognitive operating system,” where AI agents collaborate with you instead of waiting for you to type queries. Comet is not marketed as a passive viewing pane.</p><p>Comet includes an agentic AI assistant that can manage web interactions, automate workflows, and carry out multi-step tasks without continuous user input. It provides AI-powered search that serves generated answers directly, eschewing conventional results pages. A lot of processing is done locally, and privacy is given top priority [10].</p><p>Despite its potential, Comet is restricted to $200/month Perplexity Max subscribers and is still invite-only [9]. To make the transition from niche to mainstream, enormous distribution. Chrome offers exactly that.</p><h3>Echoes of Musk</h3><p>Some strategies are used in the tech theatre to completely alter the narrative rather than win hands down. Elon Musk did just that in February 2025 when he made an offer of $97.4 billion for OpenAI [11]. Since Musk wasn’t in a hurry to acquire OpenAI and it wasn’t for sale, the deal would never go through. However, Musk accomplished two goals by bringing up such a huge figure in public discourse: he skyrocketed OpenAI’s perceived market value and put Sam Altman on the defensive because he knew that any future talks would have to revolve around that amount.</p><p>Without a single share changing hands, this was valuation warfare.</p><p>The same DNA is present in Perplexity’s Chrome bid. Offering almost twice their own market capitalisation for the most popular browser in history guarantees one thing: competitors, analysts, and regulators will never forget the $34.5 billion figure. Perplexity has already established the public standard in the event that the DOJ compels Google to sell. <br> <br>Using an opponent’s momentum and the full force of the media spotlight to tip the scales is corporate judo [12].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2vr1wylpmDfDJJ9FwokgQ.jpeg" /></figure><h3>Bluff, Battle, or Both?</h3><p>It is difficult to overestimate the magnitude of the impact if this is a real acquisition attempt. Perplexity would acquire 3.45 billion users overnight and directly impact over two-thirds of internet users’ default browsing experience [13]. Chrome may develop into a proactive AI agent platform rather than just a passive window.</p><p>Even if it’s a bluff, the benefits are still striking: Perplexity solidifies its position as the sensible buyer, Chrome’s fictitious “price tag” becomes public knowledge, and the company receives weeks of unpaid, international media attention.</p><p>Additionally, it buys time if it is a deliberate diversion; rivals like Arc, Brave, and OpenAI’s own browser must now account for Perplexity’s goals in their roadmaps [14].</p><h3>The AI Browser Wars</h3><p>The humble browser has evolved beyond being merely an HTML frame. It is evolving into our digital lives’ operating system. Microsoft’s Edge Copilot makes use of extensive Windows and Office integration [15]. Leo from Brave prioritises privacy while providing multi-LLM flexibility [16]. Aria from Opera combines AI and multimedia [17]. Contextual automation is the main focus of Arc Max [18]. Additionally, OpenAI’s own browser, which is based on Chromium and has ChatGPT integrated, is anticipated to launch in a few weeks [19].</p><p>Chrome is the entire front of the house in this new arena, not just the door. The way that billions of people use the internet is determined by whoever controls it.</p><h3>Risks and Realities</h3><p>Naturally, the path ahead is far from easy. Google has not expressed a desire to sell [1], and any divestiture order may be postponed or halted by appeals [7]. The idea of an AI-first company controlling the most popular browser may irritate regulators [20]. Additionally, Perplexity is still battling media behemoths like News Corp and the BBC in court over alleged copyright violations [21].</p><h3>Win or Lose, a Win</h3><p>Perplexity will have the biggest user base in the history of consumer technology if it can manage to accomplish this. Chrome has the potential to revolutionise how we search, browse, and conduct business online by becoming the first widely used browser that is truly AI-native.</p><p>Should they lose? Perceived as a contender for the web’s infrastructure layer as well as a search competitor, they continue to walk away with the largest PR victory in their company’s history.</p><h3>The Opening Salvo</h3><p>It’s possible that history will forget August 12, 2025, as the day Chrome changed owners. However, it may recall it as the initial attempt at the AI browser wars.</p><p>Because the company that provides you with the most intelligent answers won’t have the real power in this new era.<br>The owner of the location where you ask them will be the rightful owner.</p><h3>Sources</h3><ol><li><a href="https://www.wsj.com/">https://www.wsj.com</a></li><li><a href="https://gs.statcounter.com/">https://gs.statcounter.com</a></li><li><a href="https://timesofindia.indiatimes.com/">https://timesofindia.indiatimes.com</a></li><li><a href="https://yourstory.com/">https://yourstory.com</a></li><li><a href="https://perplexity.ai/investors">https://perplexity.ai/investors</a></li><li><a href="https://www.justice.gov/opa/pr/google-monopoly-case">https://www.justice.gov/opa/pr/google-monopoly-case</a></li><li><a href="https://www.justice.gov/court-filings">https://www.justice.gov/court-filings</a></li><li><a href="https://promarket.org/">https://promarket.org</a></li><li><a href="https://techcrunch.com/">https://techcrunch.com</a></li><li><a href="https://perplexity.ai/comet">https://perplexity.ai/comet</a></li><li><a href="https://www.bloomberg.com/">https://www.bloomberg.com</a></li><li><a href="https://www.marketwatch.com/">https://www.marketwatch.com</a></li><li><a href="https://nypost.com/">https://nypost.com</a></li><li><a href="https://www.axios.com/">https://www.axios.com</a></li><li><a href="https://blogs.windows.com/msedge">https://blogs.windows.com/msedge</a></li><li><a href="https://brave.com/">https://brave.com</a></li><li><a href="https://www.opera.com/aria">https://www.opera.com/aria</a></li><li><a href="https://arc.net/">https://arc.net</a></li><li><a href="https://www.reuters.com/">https://www.reuters.com</a></li><li><a href="https://www.wired.com/">https://www.wired.com</a></li><li><a href="https://www.bbc.com/news">https://www.bbc.com/news</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f39fa7df528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built an Autoencoder with ONLY numpy]]></title>
            <link>https://akashnath29.medium.com/how-i-built-an-autoencoder-with-only-numpy-d225305654c5?source=rss-9941da589fa0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d225305654c5</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Akash Nath]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 19:51:59 GMT</pubDate>
            <atom:updated>2025-01-18T20:04:29.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how AI can learn to compress and reconstruct data — just like how your brain processes images and sounds? Picture this: You give a machine a massive image, and it figures out how to squish it down into a compact version, keeping only the essential details. But when you ask it to restore the image, it brings it back almost exactly as it was, with remarkable accuracy. Sounds like magic, right? Well, it’s all thanks to <em>autoencoders</em>, a powerful concept in deep learning.</p><p>Let me take you on a journey through the fascinating world of autoencoders, diving into the project I recently completed using the MNIST dataset, where I built an autoencoder from scratch. This blog will explain everything you need to know about autoencoders, step by step, with some cool illustrations and examples along the way.</p><h4>What is an Autoencoder?</h4><p>At its core, an autoencoder is a type of neural network used for unsupervised learning. Imagine a <em>data compression tool</em> — just like how WinRAR compresses files to save space but still allows you to open them later. In the same way, an autoencoder learns to compress data (like images) into a smaller “encoded” representation and then reconstruct it back to its original form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*ufqJ01s_sM-W-SG3TtbpXw.jpeg" /><figcaption>Figure 1: Visual Representation of an Autoencoder</figcaption></figure><p>Here’s the magic:</p><ol><li><strong>Encoder</strong>: It takes the input and compresses it into a smaller, more efficient representation (called the <em>latent space</em>).</li><li><strong>Decoder</strong>: It then takes that compressed version and reconstructs the original data from it.</li></ol><p>The real beauty of autoencoders is their ability to learn this compression and decompression by themselves, without needing explicit labels for training. They discover the most important features from the data on their own.</p><h4>A Deep Dive Into the MNIST Dataset</h4><p>The MNIST dataset is the quintessential benchmark for beginners in machine learning and computer vision. It contains 60,000 training images of handwritten digits (0–9), each 28x28 pixels in grayscale. It’s perfect for testing out a neural network, as the data is simple but still offers enough complexity for a meaningful experiment. I used a CSV format of this dataset for my project, that contained all 784 pixel values in one CSV for 60000 image each.</p><h4>What Did I Do?</h4><p>In my project, I built an autoencoder that works on the MNIST dataset with these steps:</p><ol><li><strong>Import Necessary Libraries: </strong>First, I imported Pandas to load dataset and preprocess the data, Numpy to build the whole Autoencoder and Matplotlib to visualize outputs.</li><li><strong>Preprocessing the Data</strong>: First, I loaded the MNIST dataset and preprocessed it. The images are flattened to 784 dimensions (28x28 = 784 pixels), and the pixel values are scaled between 0 and 1. This is a standard practice in deep learning to ensure that the model trains faster and more effectively.</li></ol><pre>train_data = pd.read_csv(&#39;data/mnist_train.csv&#39;)<br>test_data = pd.read_csv(&#39;data/mnist_test.csv&#39;)<br><br>train_data = train_data.drop(&#39;label&#39;, axis=1)<br>test_data = test_data.drop(&#39;label&#39;, axis=1)<br><br>train_data = train_data.values.reshape(-1, 784)<br>test_data = test_data.values.reshape(-1, 784)<br><br>train_data = train_data / 255.0<br>test_data = test_data / 255.0</pre><p>3. <strong>Activation Functions: </strong>We used two very famous activation function for this project. They are: ReLU and Sigmoid</p><p><strong>ReLU (Rectified Linear Unit): </strong>In the context of artificial neural networks, the rectifier or ReLU (rectified linear unit) activation function is an activation function defined as the non-negative part of its argument. (Source: Wikipedia)</p><p>In simple terms: it keeps only the positive values and sets negative values to zero, making the model faster and helping it learn complex patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiTYLRiRjJJU2qgHxiCQMw.jpeg" /><figcaption>Figure 2: ReLU (Source: Wikipedia)</figcaption></figure><figure><img alt="Figure 3: Graphical Representation of ReLU activation function" src="https://cdn-images-1.medium.com/max/330/1*Umx3ioWf0-gOo_B8iZ_NAQ.png" /><figcaption>Figure 3: Visual representation of ReLU (Source: Wikipedia)</figcaption></figure><p><strong>Sigmoid: </strong>A sigmoid function is any mathematical function whose graph has a characteristic S-shaped or sigmoid curve. (Source: Wikipedia)</p><p>In simple terms: It squashes any input value into a range between 0 and 1. It works like a smooth “S” shape, where very large inputs become close to 1, very small (negative) inputs become close to 0, and values around 0 are mapped near the middle, around 0.5. This makes it useful for tasks like probability prediction or binary classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*jR47hmxZSWm-Sspoyz1aOQ.jpeg" /><figcaption>Figure 4: Sigmoid Function (Source: Wikipedia)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*rPO-9tj04fr00rJhQkfmCw.png" /><figcaption>Figure 5: Visual Representation of Sigmoid function (Source: Wikipedia)</figcaption></figure><pre>def relu(x):<br>    return np.maximum(0.01 * x, x) # Leaky ReLU<br><br>def sigmoid(x):<br>    return 1 / (1 + np.exp(-x))</pre><p>4. <strong>Loss Function: </strong>Binary Cross-Entropy (BCE) loss is a loss function used in binary classification tasks to measure the difference between the predicted probabilities and the actual labels (0 or 1). It calculates the negative average of the log-likelihood of the true labels given the predicted probabilities. Mathematically, for nn samples, it is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*yzhan5JFBFzL0ZKxFAZm4w.png" /><figcaption>Binary Cross Entropy Loss</figcaption></figure><p>Here, yi is the true label (0 or 1), and yi^ is the predicted probability. BCE penalizes wrong predictions more heavily when the predicted probability is confident but incorrect, making it ideal for binary classification problems.</p><pre>def bce_loss(y_true, y_pred):<br>    epsilon = 1e-12<br>    y_pred = np.clip(y_pred, epsilon, 1 - epsilon)<br><br>    loss = -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))<br>    return loss</pre><p>5. <strong>Calculating Accuracy:</strong></p><pre>def calculate_accuracy(y_true, y_pred, threshold=0.1):<br>    diff = np.abs(y_true - y_pred)<br>    correct_features = (diff &lt; threshold).astype(int)<br>    sample_accuracy = np.mean(correct_features, axis=1)<br>    overall_accuracy = np.mean(sample_accuracy) * 100<br>    return overall_accuracy</pre><p>This function measures the accuracy of predictions by comparing them to the true values within a predefined threshold. The idea is to check whether the predicted values are close enough to the actual values, allowing for some margin of error (defined by the threshold).</p><p>For each prediction, the absolute difference between the predicted value and the actual value is calculated. If this difference is smaller than the threshold, the prediction is considered correct. Accuracy is then calculated at two levels:</p><ul><li><strong>Feature-level accuracy</strong>: The proportion of correctly predicted features within each sample.</li><li><strong>Overall accuracy</strong>: The average accuracy across all samples, expressed as a percentage.</li></ul><p>By setting a small threshold, this method ensures that predictions are not only correct but also precise, making it useful for tasks where slight deviations matter.</p><p>6. <strong>Initialization of Parameters: </strong>The initialization of parameters is a vital step in constructing a neural network, as it sets the starting point for learning. In the provided example, the weights (W_{1}) are initialized using a random distribution scaled by \sqrt{\frac{2}{\text{input size}}}. This scaling is based on the He initialization method, which helps maintain stable gradients during training, particularly when using ReLU activation functions. The biases (b_{1}) are initialized to zero, ensuring that the initial output of the network is unbiased. These initialized parameters serve as the foundation for the training process.</p><pre>def init_params(input_size, output_size):<br>    W1 = np.random.randn(output_size, input_size) * np.sqrt(2. / input_size)<br>    b1 = np.zeros((output_size, 1))<br>    return W1, b1</pre><p>7. <strong>Defining Dense Layer: </strong>Defining Dense Layer</p><p>The dense layer in a neural network is a fully connected layer where each neuron is connected to every neuron in the previous layer. In the provided example, the dense layer is implemented by performing a matrix multiplication between the input (x) and the weights (w) followed by adding the bias (b). This operation calculates the weighted sum of inputs and applies the bias, which serves as the output for the layer. The result is then passed to the next layer in the network, where activation functions or other operations can be applied. This process forms the core of a neural network’s forward pass.</p><pre>def dense(x, w, b):<br>    return np.dot(x, w) + b</pre><p>8. <strong>Building the Optimizer: </strong>Building the Optimizer: A Beginner-Friendly Explanation</p><p>In machine learning, training a model means adjusting its parameters (such as weights and biases) to minimize the error (loss) between the predicted and actual values. Optimizers are algorithms that help in this process by adjusting the model’s parameters to reduce the loss step by step. One of the most commonly used optimizers is <strong>Adam</strong> (Adaptive Moment Estimation). Let’s break down how it works with a beginner-friendly explanation and the math behind it.</p><p><strong>What is Adam Optimizer: </strong>Adam is an advanced optimization algorithm that combines two ideas:</p><ol><li><strong>Momentum</strong> (which helps accelerate learning in the right direction).</li><li><strong>Scaling the learning rate</strong> for each parameter (which helps adapt the learning rate during training).</li></ol><p>It uses two important things to update the parameters:</p><ul><li><strong>First moment estimate</strong>: The average of the past gradients (like momentum).</li><li><strong>Second moment estimate</strong>: The average of the squared gradients (like scaling based on how large the gradient is).</li></ul><p>These moments are used to update the parameters in a way that ensures faster convergence and avoids issues like overshooting or slow learning.</p><p><strong>Mathematics Behind Adam Optimizer: </strong>Let’s go over the math involved in the Adam optimizer:</p><p><strong>i. First Moment (m)</strong>: This is the running average of the gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*_OWuTIL_v0ybdjFN6W2VAg.png" /></figure><p>where:</p><ul><li>m_{t} is the updated first moment (mean of gradients).</li><li>\beta_1 is a constant (typically 0.9).</li><li>g_{t} is the gradient at time step tt.</li><li>m_{t-1} is the previous value of the first moment.</li></ul><p><strong>ii. Second Moment (v)</strong>: This is the running average of the squared gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*nJo5e6UO7aU0cuEQX9CaVw.png" /></figure><p>where:</p><ul><li>v_t is the updated second moment (mean of squared gradients).</li><li>\beta_2 is a constant (typically 0.999).</li></ul><p><strong>iii. Bias Correction</strong>: Since m_{t} and v_{t} are initialized as zeros, the estimates are biased toward zero, especially during the early stages of training. To correct this, we apply bias correction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*93ocQSq8qcV3-BSa2C9odw.png" /></figure><p>where:</p><ul><li>t is the current time step.</li><li>\hat{m_t} and \hat{v_t} are the bias-corrected first and second moments.</li></ul><p><strong>iv. Parameter Update</strong>: Once we have the corrected moments, the parameters (weights \theta) are updated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*H9A_86Av7xSWiMS-iqxdog.png" /></figure><p>where:</p><ul><li>\theta_t is the current parameter (weight).</li><li>\alpha is the learning rate (typically 0.001).</li><li>\epsilon is a small constant to avoid division by zero (usually 1 \times 10^{-8}).</li></ul><p>This update rule helps in adjusting the parameters by considering both the past gradients (momentum) and the squared gradients (adaptive learning rate). It allows Adam to make updates that are well-adjusted for each parameter, ensuring fast and stable training.</p><p><strong>Why Use Adam: </strong>Adam is widely used because it adapts to different kinds of problems and can work well with sparse gradients (where only a few features are important). It is often more efficient and requires less tuning compared to other optimizers like gradient descent. Here’s why Adam is effective:</p><ol><li>It adapts the learning rate for each parameter.</li><li>It considers both the momentum (past gradients) and the scaling of gradients (variance).</li><li>It works well even with large datasets and non-stationary objectives.</li></ol><pre>class AdamOptimizer:<br>    def __init__(self, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):<br>        self.lr = lr<br>        self.beta1 = beta1<br>        self.beta2 = beta2<br>        self.epsilon = epsilon<br>        self.m_w = 0<br>        self.v_w = 0<br>        self.m_b = 0<br>        self.v_b = 0<br>        self.t = 0<br>        <br>    def update(self, param, grad, m, v):<br>        self.t += 1<br>        m = self.beta1 * m + (1 - self.beta1) * grad<br>        v = self.beta2 * v + (1 - self.beta2) * (grad ** 2)<br>        <br>        m_hat = m / (1 - self.beta1 ** self.t)<br>        v_hat = v / (1 - self.beta2 ** self.t)<br>        <br>        param -= self.lr * m_hat / (np.sqrt(v_hat) + self.epsilon)<br>        return param, m, v</pre><p>9. <strong>Building the Encoder: </strong>In machine learning, particularly in neural networks like autoencoders, <strong>Encoders</strong> play a crucial role in transforming input data into a form that is easier for the model to understand and work with. The encoder takes the input data, processes it, and compresses it into a smaller, more abstract representation, typically referred to as the <strong>latent space</strong> or <strong>feature space</strong>. Let’s break down how the encoder works and understand its components step by step.</p><p><strong>What Does the Encoder Do: </strong>The <strong>Encoder</strong>’s primary goal is to learn how to compress data (like an image, text, or any high-dimensional input) into a more compact and informative representation. This representation is smaller, easier to handle, and contains the most important features of the data. The Encoder passes the data through a series of transformations until it is encoded into this reduced representation.</p><p><strong>Components of the Encoder:</strong></p><p><strong>i. Weights and Biases</strong>: These are parameters that the model learns during training to adjust how the data is transformed.</p><ul><li>The <strong>weights</strong> control how each input feature affects the output.</li><li>The <strong>biases</strong> help shift the outputs to fit the data better.</li></ul><p>In the code, the encoder uses these weights and biases during the forward pass to process the input data.</p><p><strong>ii. Optimizer</strong>: The optimizer helps adjust the weights and biases to minimize the error during training. In the encoder, we use the <strong>Adam optimizer</strong> to do this efficiently.</p><p><strong>Workflow of the Encoder: </strong>Now, let’s walk through the steps involved in the Encoder’s forward and backward passes:</p><p><strong>a. Initialization</strong>:</p><ul><li>The encoder is initialized with the input size, hidden size, and optimizer. It also initializes the weights (W_1) and biases (b_1) for the first layer, which will be used to process the data.</li><li>The initial moment estimates (used by the optimizer) are also set to zero.</li></ul><p><strong>b. Forward Pass</strong>:</p><ul><li>During the <strong>forward pass</strong>, the encoder processes the input data (x) through a series of transformations:</li><li><strong>Linear Transformation</strong>: First, the input data (x) is passed through a dense layer, which performs a linear transformation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*Y-tPaH0U80EMtVPDBn6nqg.png" /></figure><p>where:</p><ul><li>W_1 are the weights,</li><li>b_1 is the bias,</li><li>x is the input data.</li><li><strong>Activation Function (ReLU)</strong>: The result of the linear transformation (z_1) is then passed through the ReLU activation function, which introduces non-linearity:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*tW0jb_2pip2zye3W1GzN6g.png" /></figure><p>The ReLU function keeps positive values as they are, while it sets negative values to zero. This helps the model learn complex patterns.</p><p>The final output of the encoder (a_1) is the encoded representation of the input data, which contains the important features in a compressed form.</p><p><strong>c. Backward Pass</strong>:</p><ul><li>The backward pass is used to calculate the <strong>gradients</strong> (or derivatives) that tell the model how to update its parameters (weights and biases) to minimize the loss (error). The key steps are:</li><li><strong>Compute Gradients</strong>: The encoder calculates the gradient of the loss with respect to the weights and biases. These gradients represent how much each weight and bias contributed to the error.</li><li><strong>Derivative of ReLU</strong>: The encoder uses the derivative of the ReLU activation to adjust the gradients. This derivative tells us how the activation function behaves with respect to the input:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*wITVEEQYQbgXleXjtkoCMg.png" /></figure><ul><li><strong>Calculate Gradients for Weights and Biases</strong>: The gradients are then used to compute how much the weights and biases need to change to reduce the error. This is done using the chain rule in calculus.</li></ul><p><strong>d. Update Weights and Biases</strong>:</p><ul><li>After calculating the gradients, the optimizer (Adam) is used to update the weights and biases. Adam takes into account the past gradients (momentum) and the squared gradients (adaptive learning rates), helping the model update its parameters more efficiently.</li><li>The update formula for weights and biases is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*FRuIk0iNTdJM046JRIrO3w.png" /></figure><p>where:</p><ul><li>W_1 is the weight matrix,</li><li>\alpha is the learning rate,</li><li>\hat{v_1} and m1^\hat{m_1} are the bias-corrected moment estimates from Adam.</li></ul><pre>class Encoder:<br>    def __init__(self, input_size, hidden_size, optimizer):<br>        self.input_size = input_size<br>        self.hidden_size = hidden_size<br>        self.optimizer = optimizer<br>        self.W1, self.b1 = init_params(input_size, hidden_size)<br>        self.m_w1 = self.v_w1 = np.zeros_like(self.W1)<br>        self.m_b1 = self.v_b1 = np.zeros_like(self.b1)<br><br>    def forward(self, x):<br>        self.x = x<br>        self.z1 = dense(x, self.W1.T, self.b1.T)<br>        self.a1 = relu(self.z1)<br>        return self.a1<br>    <br>    def backward(self, y):<br>        m = y.shape[0]<br>        dz1_raw = np.dot(self.W1, self.x.T)<br>        self.dz1 = dz1_raw.T * (self.a1 &gt; 0)<br>        self.dW1 = np.dot(self.dz1.T, self.x) / m<br>        self.db1 = np.sum(self.dz1, axis=0, keepdims=True).T / m<br><br>    def update(self):<br>        self.W1, self.m_w1, self.v_w1 = self.optimizer.update(self.W1, self.dW1, self.m_w1, self.v_w1)<br>        self.b1, self.m_b1, self.v_b1 = self.optimizer.update(self.b1, self.db1, self.m_b1, self.v_b1)</pre><p>10. <strong>Building the Decoder: </strong>The <strong>Decoder</strong> is the second part of the autoencoder architecture. It takes the compressed and abstract representation generated by the <strong>Encoder</strong> and tries to reconstruct the original input data. The decoder’s job is to expand the compressed data back to its original form or some approximated version of it.</p><p><strong>Components of the Decoder:</strong></p><p><strong>i. Weights and Biases</strong>: Like the encoder, the decoder has weights and biases that are learned during training. These parameters determine how the decoder reconstructs the data.</p><p><strong>ii. Optimizer</strong>: The optimizer, in this case, the <strong>Adam optimizer</strong>, adjusts the weights and biases during training to minimize the reconstruction error.</p><p><strong>Workflow of the Decoder: </strong>Now, let’s go step-by-step through the operations of the decoder:</p><p><strong>i. Initialization</strong>:</p><ul><li>When the <strong>Decoder</strong> is initialized, it receives the <strong>hidden size</strong> (size of the encoded representation) and <strong>output size</strong> (size of the original data) as input.</li><li>The decoder’s parameters, like weights (W_2) and biases (b_2), are initialized using the init_params() function.</li><li>The moment estimates for the optimizer are also initialized to zero.</li></ul><p><strong>ii. Forward Pass</strong>:</p><ul><li>The <strong>forward pass</strong> takes the encoded representation (x) from the encoder and processes it to reconstruct the data.</li><li>First, the input data is passed through a dense layer (just like the encoder):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*oN1rccltmiCVi3C7SrxEKQ.png" /></figure><p>where:</p><ul><li>W_2 is the weight matrix,</li><li>b_2 is the bias,</li><li>x is the input from the encoder (encoded data).</li><li>Next, the output of this linear transformation (z_2) is passed through a <strong>sigmoid activation function</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*cmYQYFiXjATlTd9-DxOwQw.png" /></figure><p>The sigmoid function squashes the output into a range between 0 and 1, which is typically suitable for binary data. For continuous data, sigmoid still helps by squashing the output between 0 and 1.</p><ul><li>The final output (a_2) is the decoder’s reconstruction of the original data, which should be as close as possible to the input data.</li></ul><p><strong>iii. Backward Pass</strong>:</p><ul><li>During the <strong>backward pass</strong>, the decoder computes the gradients of the loss with respect to its parameters (weights and biases). The steps involved are:</li><li><strong>Compute the error (difference)</strong>: The difference between the decoder’s output (a_2) and the actual target values (y) is calculated:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*edlCFAl7q3RtisanjWnVlg.png" /></figure><p>This error (\delta_2) tells us how far the predicted output is from the true values.</p><ul><li><strong>Calculate gradients</strong>: Using the error, we compute the gradients with respect to the weights (W_2) and biases (b_2):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*KZUiQEgGKVY1zJ59rZZo2Q.png" /></figure><p>where:</p><ul><li>m is the number of samples,</li><li>\delta_2 is the error calculated above.</li><li>The bias gradient is computed as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*xJ8FNgtsQ5QHeV9xhgcf0Q.png" /></figure><p><strong>iv. Update Weights and Biases</strong>:</p><ul><li>After calculating the gradients, the decoder updates its weights and biases using the <strong>Adam optimizer</strong>. This optimizer uses the gradients to adjust the parameters in a way that minimizes the reconstruction error.</li><li>The update for each parameter is done using the following formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*LTuipVNTE4JPr-6VXEky2Q.png" /></figure><p>where:</p><ul><li>W_2 is the weight matrix,</li><li>\alpha is the learning rate,</li><li>\hat{m_2} and \hat{v_2} are the bias-corrected moment estimates from Adam.</li></ul><pre>class Decoder:<br>    def __init__(self, hidden_size, output_size, optimizer):<br>        self.hidden_size = hidden_size<br>        self.output_size = output_size<br>        self.optimizer = optimizer<br>        self.W2, self.b2 = init_params(hidden_size, output_size)<br>        self.m_w2 = self.v_w2 = np.zeros_like(self.W2)<br>        self.m_b2 = self.v_b2 = np.zeros_like(self.b2)<br><br>    def forward(self, x):<br>        self.x = x<br>        self.z2 = dense(x, self.W2.T, self.b2.T)<br>        self.a2 = sigmoid(self.z2)<br>        return self.a2<br>    <br>    def backward(self, y):<br>        m = y.shape[0]<br>        self.dz2 = self.a2 - y<br>        self.dW2 = np.dot(self.dz2.T, self.x) / m<br>        self.db2 = np.sum(self.dz2, axis=0, keepdims=True).T / m<br><br>    def update(self):<br>        self.W2, self.m_w2, self.v_w2 = self.optimizer.update(self.W2, self.dW2, self.m_w2, self.v_w2)<br>        self.b2, self.m_b2, self.v_b2 = self.optimizer.update(self.b2, self.db2, self.m_b2, self.v_b2)</pre><h3>Building the Autoencoder</h3><p>To create the Autoencoder, we combine three core components: the <strong>Encoder</strong>, the <strong>Decoder</strong>, and the <strong>Optimizer</strong>. These components work together to compress the input data into a latent space representation and then reconstruct the data from that compressed form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Dl0dd6cKkXyY5W1uNmc85Q.jpeg" /><figcaption>Figure 6: Assembling the Autoencoder</figcaption></figure><p>The <strong>Encoder</strong> is the first part of the Autoencoder. It takes the input data and transforms it into a lower-dimensional space, which is known as the latent space. It achieves this through a dense layer followed by a ReLU activation. The weights and biases in this layer are initialized using a method (init_params), which helps in the transformation process. The encoder&#39;s main task is to learn a compressed representation of the data. The forward pass of the encoder calculates the linear transformation of the input, and the activation function (ReLU) introduces non-linearity.</p><p>The <strong>Decoder</strong>, on the other hand, takes this compressed representation from the encoder and reconstructs it to approximate the original input. It also uses a dense layer, but the activation function here is sigmoid, which helps in bringing the output back to the same range as the original input data. The decoder’s forward pass computes the output by performing a linear transformation of the encoder’s output and applying the sigmoid activation.</p><p>For optimizing the learning process, we use the <strong>AdamOptimizer</strong>. The optimizer helps in adjusting the weights and biases of both the encoder and decoder by minimizing the reconstruction error. The Adam optimizer is efficient for training deep networks and handles the weight updates based on the gradients computed during backpropagation. The optimizer uses momentum and adaptive learning rates, making it faster and more stable during training compared to traditional stochastic gradient descent.</p><h4>Training the Autoencoder</h4><p>Training the autoencoder involves several steps where the model learns to minimize the reconstruction error between the input data and the reconstructed output. During training, the autoencoder is fed with batches of data, and the model computes the forward and backward passes in each iteration.</p><p>The <strong>forward pass</strong> involves passing the input through the encoder to get the compressed representation and then through the decoder to get the reconstructed output. The <strong>loss function</strong> (binary cross-entropy in this case) measures the difference between the input and the reconstructed data. This loss guides the backpropagation process.</p><p>In the <strong>backward pass</strong>, we compute the gradients of the loss with respect to the weights and biases of both the encoder and decoder. These gradients are then used to update the weights and biases using the Adam optimizer. The optimizer adjusts the parameters to reduce the reconstruction error over time.</p><p>The training process repeats for multiple epochs, where in each epoch, the model is trained over batches of data. After every epoch, the average loss and the accuracy are printed to monitor the progress. The accuracy is computed to show how well the model is reconstructing the input.</p><p>At the end of training, the autoencoder learns to compress the input data and reconstruct it accurately. The performance of the model is tracked through the loss and accuracy metrics plotted over the epochs, providing a clear visualization of how the model improves during training.</p><pre>class Autoencoder:<br>    def __init__(self, input_size, hidden_size, optimizer):<br>        self.encoder = Encoder(input_size, hidden_size, optimizer)<br>        self.decoder = Decoder(hidden_size, input_size, optimizer)<br>        self.optimizer = optimizer<br>        self.loss_history = []<br>        self.total_params = self.calculate_total_params()<br>        <br>    def calculate_total_params(self):<br>        encoder_params = np.prod(self.encoder.W1.shape) + np.prod(self.encoder.b1.shape)<br>        decoder_params = np.prod(self.decoder.W2.shape) + np.prod(self.decoder.b2.shape)<br>        return encoder_params + decoder_params<br>    <br>    def summary(self):<br>        # Header<br>        print(&quot;------------------------------------------------------------&quot;)<br>        print(f&quot;{&#39;Layer (Type)&#39;:&lt;20} {&#39;Output Shape&#39;:&lt;20} {&#39;Param #&#39;:&lt;10}&quot;)<br>        print(&quot;============================================================&quot;)<br>        <br>        # Encoder details<br>        encoder_params = np.prod(self.encoder.W1.shape) + np.prod(self.encoder.b1.shape)<br>        print(f&quot;Encoder (Dense):{&#39;&#39;:&lt;9} ({self.encoder.hidden_size},)       {encoder_params:&lt;10}&quot;)<br>        <br>        # Decoder details<br>        decoder_params = np.prod(self.decoder.W2.shape) + np.prod(self.decoder.b2.shape)<br>        print(f&quot;Decoder (Dense):{&#39;&#39;:&lt;9} ({self.decoder.output_size},)      {decoder_params:&lt;10}&quot;)<br>        <br>        # Footer<br>        print(&quot;============================================================&quot;)<br>        print(f&quot;Total Parameters: {self.total_params}&quot;)<br>        print(f&quot;Trainable Parameters: {self.total_params}&quot;)<br>        print(f&quot;Non-trainable Parameters: 0&quot;)<br>        print(&quot;------------------------------------------------------------&quot;)<br>        <br>    def forward(self, x):<br>        self.encoded = self.encoder.forward(x)<br>        self.decoded = self.decoder.forward(self.encoded)<br>        return self.decoded<br>    <br>    def backward(self, y):<br>        self.decoder.backward(y)<br>        self.decoder.update()<br>        self.encoder.backward(y)<br>        self.encoder.update()<br>        <br>    def train(self, x, y, epochs, batch_size, threshold=0.1):<br>        m = x.shape[0]<br>        self.accuracy_history = []<br><br>        for epoch in range(epochs):<br>            epoch_loss = 0<br>            all_predictions = []<br>            all_true_values = []<br><br>            for i in range(0, m, batch_size):<br>                x_batch = x[i:i + batch_size]<br>                y_batch = y[i:i + batch_size]<br>                <br>                self.forward(x_batch)<br>                self.backward(y_batch)<br><br>                batch_loss = bce_loss(y_batch, self.decoded)<br>                epoch_loss += batch_loss<br><br>                all_predictions.append(self.decoded)<br>                all_true_values.append(y_batch)<br><br>            avg_epoch_loss = epoch_loss / (m // batch_size)<br>            self.loss_history.append(avg_epoch_loss)<br><br>            all_predictions = np.vstack(all_predictions)<br>            all_true_values = np.vstack(all_true_values)<br><br>            accuracy = calculate_accuracy(all_true_values, all_predictions, threshold)<br>            self.accuracy_history.append(accuracy)<br><br>            print(&quot;-----------------------------------------------&quot;)<br>            print(f&#39;Epoch {epoch + 1}/{epochs} - Loss: {avg_epoch_loss:.4f}, Accuracy: {accuracy}%&#39;)<br><br>        self.plot_metrics()<br><br>            <br>    def predict(self, x):<br>        return self.forward(x)<br>    <br>    def evaluate(self, x, y):<br>        predictions = self.predict(x)<br>        loss = bce_loss(y, predictions)<br>        return loss<br>    <br>    def plot_metrics(self):<br>        plt.figure(figsize=(10, 5))<br>        plt.plot(self.loss_history, label=&quot;Training Loss&quot;, color=&#39;blue&#39;)<br>        plt.xlabel(&#39;Epoch&#39;)<br>        plt.ylabel(&#39;Loss&#39;)<br>        plt.title(&#39;Training Loss Over Epochs&#39;)<br>        plt.legend()<br>        plt.grid()<br>        plt.show()<br><br>        plt.figure(figsize=(10, 5))<br>        plt.plot(self.accuracy_history, label=&quot;Training Accuracy&quot;, color=&#39;orange&#39;)<br>        plt.xlabel(&#39;Epoch&#39;)<br>        plt.ylabel(&#39;Accuracy (%)&#39;)<br>        plt.title(&#39;Training Accuracy Over Epochs&#39;)<br>        plt.legend()<br>        plt.grid()<br>        plt.show()<br><br><br><br><br>learning_rate = 0.001<br>batch_size = 64<br>epochs = 300 <br><br>optimizer = AdamOptimizer(lr=learning_rate)            <br>autoencoder = Autoencoder(784, 256, optimizer)<br>autoencoder.summary()<br>autoencoder.train(train_data, train_data, epochs, batch_size)</pre><h3>Output</h3><p>After training the autoencoder for 300 epochs, the model achieved a loss of <strong>0.0868</strong> and an accuracy of <strong>90.2%</strong>, demonstrating significant progress. Initially, in the first epoch, the loss was <strong>0.3840</strong>, and the accuracy was <strong>21.5%</strong>, indicating that the model was just beginning to learn and adapt to the data. As the training continued, the optimizer gradually adjusted the weights, reducing the error and increasing the model’s accuracy. This shows how the model improved its predictions over time, reflecting the effectiveness of the training process and the optimizer in minimizing the loss and improving the performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*7ajvaXAAkf0v7Dpy_W74Ng.png" /><figcaption>Figure 7: Epoch 300</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2F0AfkYonH5JCNckqvNOXQ.jpeg" /><figcaption>Figure 8: Training Loss and Accuracy Graph</figcaption></figure><h3>Testing the Model</h3><p>Testing the model involves evaluating its performance on the test data and visualizing how well the autoencoder can reconstruct the input images. First, we calculate the test loss using the evaluate method, which computes the loss between the original test images and their reconstructed versions. The loss provides a measure of how well the model generalizes to unseen data.</p><p>After evaluating the loss, we visualize the results by displaying a set of 10 images. For each image, we show three parts:</p><ol><li><strong>Original Image</strong>: This is the input image from the test dataset.</li><li><strong>Encoded Image</strong>: This represents the encoded feature map, where the autoencoder compresses the image to a smaller size. It’s the output after passing the image through the encoder layer.</li><li><strong>Reconstructed Image</strong>: This is the final output after the decoder reconstructs the image from the encoded features.</li></ol><p>The process of displaying the images side by side helps to compare how well the autoencoder is able to learn and reconstruct the images, providing an intuitive understanding of the model’s performance. The closer the reconstructed images are to the original images, the better the model has learned to encode and decode the data.</p><pre># Testing the model<br>test_loss = autoencoder.evaluate(test_data, test_data)<br>print(f&#39;Test Loss: {test_loss}&#39;)<br><br>n = 10 <br>plt.figure(figsize=(20, 6))<br><br>for i in range(n):<br>    # Original Image<br>    ax = plt.subplot(3, n, i + 1)<br>    plt.title(&quot;Original&quot;)<br>    plt.imshow(test_data[i].reshape(28, 28))<br>    plt.gray()<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)<br>    <br>    # Encoded Image<br>    encoded_data = autoencoder.encoder.forward(test_data)<br>    ax = plt.subplot(3, n, i + 1 + n) <br>    plt.title(&quot;Encoded&quot;)<br>    plt.imshow(encoded_data[i].reshape(16, 16))<br>    plt.gray()<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)<br><br>    # Reconstructed Image<br>    reconstructed_data = autoencoder.predict(test_data)<br>    ax = plt.subplot(3, n, i + 1 + 2 * n) <br>    plt.title(&quot;Reconstructed&quot;)<br>    plt.imshow(reconstructed_data[i].reshape(28, 28))<br>    plt.gray()<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8vQcqk348kQC5aP9q20oQ.png" /><figcaption>Figure 9: Output</figcaption></figure><h3>Conclusion</h3><p>In conclusion, this autoencoder model demonstrates the power of unsupervised learning in compressing and reconstructing data. By effectively utilizing encoder-decoder architecture and leveraging the Adam optimizer, we’ve built a robust model that not only achieves impressive accuracy but also showcases the potential of neural networks in handling complex data. The journey from training with a loss of 0.38 to achieving 90% accuracy highlights the model’s capability to learn and improve over time, making it a valuable tool for tasks like data denoising, anomaly detection, and dimensionality reduction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d225305654c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Generate Images using GAN]]></title>
            <link>https://akashnath29.medium.com/lets-generate-images-using-gan-2df5d747812a?source=rss-9941da589fa0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df5d747812a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <dc:creator><![CDATA[Akash Nath]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 17:37:47 GMT</pubDate>
            <atom:updated>2024-10-06T17:37:47.686Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ever wanted to generate cool images using AI? No, I am not talking about any existing Saas product or any API, I am talking about creating the network by YOURSELF!!! Today I will walk you through the necessary steps to create a working Generative Adversarial Network, also known as GANs. So without furthur a do, let’s dive into this.</p><h3>Generative Adversarial Network</h3><p>A Generative Adversarial Network, a.k.a GAN has two main parts: Generator, and the Discriminator. The Generator generates image from a lower dimensional latent space representation, and then the Discriminiator checks wheather the generated image is REAL OR FAKE compared to some high dimensional image data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmS-q2trk0loCJPZ6edp_Q.png" /><figcaption>Figure 1: Basic Structure of GAN</figcaption></figure><p>Based on the feedback of the Discriminator, we jump to the backward propagation step, where we change the weight and bias of the network in such a way so that the generated image seems so real that even the Discriminator tells it’s real. In this training process both the Generator and Discriminator gets better at generating and deciding whether the image is real or not.</p><h3>Building GAN</h3><p>Building GAN is not so tough work. All we need as prerequisite are: 1. Basic Python, 2. Basic concepts of Neural Networks.</p><h4>Necessary Imports</h4><p>To build the GAN, we will be using vanilla Tensorflow and Keras. We will import them along with some other libraries before we proceed to next step</p><pre>import tensorflow as tf<br>from tensorflow.keras import layers<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><h4>Data Loading and Preprocessing</h4><p>In this project I will be using Fasion MNIST dataset as the training and testing data. Fashion MNIST contains 70000 images (60000 training image, 10000 testing image) of different dresses and other fasion elements of size 28 x 28 px.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*QIQM35OvjQ1rCK7sv6zGOw.png" /><figcaption>Figure 2: Fasion MNIST</figcaption></figure><p>To load the data, we will use the built in function of keras</p><pre>(train_images, _), (_, _) = tf.keras.datasets.fashion_mnist.load_data()<br>train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype(&#39;float32&#39;)<br>train_images = (train_images - 127.5) / 127.5<br><br>BUFFER_SIZE = 60000<br>BATCH_SIZE = 256<br><br>train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)</pre><p>We will first load the image arrays only as GAN trains on unsupervised learing. After loading the data we will normalize the values of each pixel between [-1, 1]. After this step to improve the effectiveness and efficiency of training the network, we build a dataset utilising solely the training images. In order to prevent bias during training due to data order, the train_images array is randomly shuffled. The shuffled data is then divided into smaller batches, each of which has 256 photos. We can feed the data to the network in reasonable pieces thanks to this batching mechanism, which optimises memory utilisation and expedites the training process.</p><h4>Generator Network</h4><p>The Generator network in an Generative Adversarial Network generates the images from the low dimensional data. The generator creates an image that resembles the actual data by using a random noise vector as input. After reshaping the output and starting with a fully connected layer, we employ multiple Conv2DTranspose layers to upsample the image to the desired size.</p><pre>def make_generator_model():<br>    model = tf.keras.Sequential([<br>        layers.Dense(7*7*256, use_bias=False, input_shape=(100,)),<br>        layers.BatchNormalization(),<br>        layers.LeakyReLU(),<br>        <br>        layers.Reshape((7, 7, 256)),<br>        layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding=&#39;same&#39;, use_bias=False),<br>        layers.BatchNormalization(),<br>        layers.LeakyReLU(),<br>        <br>        layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding=&#39;same&#39;, use_bias=False),<br>        layers.BatchNormalization(),<br>        layers.LeakyReLU(),<br>        <br>        layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding=&#39;same&#39;, use_bias=False, activation=&#39;tanh&#39;)<br>    ])<br>    return model</pre><p>The process begins with a dense layer that creates a 7x7x256 tensor from a 100-dimensional noise vector. This tensor serves as a preliminary design for an image with low resolution. After using batch normalisation to stabilise training, the Leaky ReLU activation function is used to introduce non-linearity and prevent neurones from becoming dormant.</p><p>After reshaping the output into a 7x7 image with 256 channels, the image size is gradually increased while the depth is decreased using transposed convolutional layers (Conv2DTranspose). While the following layer expands to 14x14 with 64 channels, the first transposed layer keeps the size at 7x7 but decreases the number of channels to 128. This technique is repeated until the last layer yields an image that is 28x28x1, the same size as the Fashion MNIST photos. The generator can produce data that appears realistic since the tanh activation function makes sure pixel values are scaled between -1 and 1, matching the normalised input images.</p><h4>Discriminator Network</h4><p>The Discriminator works as an examinar, that examins the generated image, compares with the original image and then concludes whether the generated image is real or not.</p><pre>def make_discriminator_model():<br>    model = tf.keras.Sequential([<br>        layers.Conv2D(64, (5, 5), strides=(2, 2), padding=&#39;same&#39;, input_shape=[28, 28, 1]),<br>        layers.LeakyReLU(),<br>        layers.Dropout(0.3),<br>        <br>        layers.Conv2D(128, (5, 5), strides=(2, 2), padding=&#39;same&#39;),<br>        layers.LeakyReLU(),<br>        layers.Dropout(0.3),<br>        <br>        layers.Flatten(),<br>        layers.Dense(1)<br>    ])<br>    return model</pre><p>Determining if an image is real (from the training dataset) or fake (produced by the generator) is the main job of the discriminator. It begins with a 2D convolutional layer that scans over the input pictures (28x28 pixels with 1 channel for greyscale) using 64 filters of size 5x5 in order to identify features like edges and textures. By reducing the output size by half, the strides=(2, 2) argument downsamples the image. Next, a Leaky ReLU activation function is employed, which mitigates the problems associated with inactive neurones and permits non-linear transformations. To avoid overfitting, a dropout layer with a 30% rate is incorporated, which randomly sets certain neurones to zero during training.</p><p>The model then adds a second convolutional layer with 128 filters and applies Leaky ReLU and dropout in the same way. Following these convolutional layers, the output is prepared for the following layer by being flattened into a one-dimensional array. Ultimately, a single value that indicates the probability that the input image is authentic (nearer to 1) or fraudulent (nearer to 0) is produced by a dense layer. All things considered, the discriminator uses this sequence of convolutional, activation, and dropout layers to efficiently learn to discriminate between actual and produced images.</p><h4>Loss Functions</h4><p>Both the generator and the discriminator use <strong>binary cross-entropy</strong> as the loss function. The generator wants to “fool” the discriminator, so its loss measures how well it can make the discriminator classify fake images as real. The discriminator’s loss is calculated based on how well it can distinguish between real and fake images.</p><pre>cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)<br><br>def generator_loss(fake_output):<br>    return cross_entropy(tf.ones_like(fake_output), fake_output)<br><br>def discriminator_loss(real_output, fake_output):<br>    real_loss = cross_entropy(tf.ones_like(real_output), real_output)<br>    fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)<br>    total_loss = real_loss + fake_loss<br>    return total_loss</pre><h4>Optimizers</h4><p>We use the <strong>Adam optimizer</strong> for both the generator and discriminator, with a learning rate of 1e-4 to ensure smooth and stable training.</p><pre>generator_optimizer = tf.keras.optimizers.Adam(1e-4)<br>discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)</pre><h4>Training Procedure</h4><p>The generator and discriminator are switched between during the training cycle. The generator creates fictitious graphics from random noise for every batch. After evaluating both actual and phoney images, the discriminator computes the losses.</p><pre>@tf.function<br>def train_step(images):<br>    noise = tf.random.normal([BATCH_SIZE, 100])<br><br>    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:<br>        generated_images = generator(noise, training=True)<br><br>        real_output = discriminator(images, training=True)<br>        fake_output = discriminator(generated_images, training=True)<br><br>        gen_loss = generator_loss(fake_output)<br>        disc_loss = discriminator_loss(real_output, fake_output)<br><br>    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)<br>    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)<br><br>    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))<br>    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))<br><br>def generate_and_save_images(model, epoch, test_input):<br>    predictions = model(test_input, training=False)<br>    <br>    fig = plt.figure(figsize=(4, 4))<br>    <br>    for i in range(predictions.shape[0]):<br>        plt.subplot(4, 4, i+1)<br>        plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap=&#39;gray&#39;)<br>        plt.axis(&#39;off&#39;)<br>    <br>    plt.savefig(f&#39;image_at_epoch_{epoch:04d}.png&#39;)<br>    plt.show()<br><br>def train(dataset, epochs):<br>    for epoch in range(epochs):<br>        gen_loss_epoch = []<br>        disc_loss_epoch = []<br>        <br>        for image_batch in dataset:<br>            gen_loss, disc_loss = train_step(image_batch)<br>            gen_loss_epoch.append(gen_loss)<br>            <br>        generator_losses.append(np.mean(gen_loss_epoch))<br>        discriminator_losses.append(np.mean(disc_loss_epoch))<br>        <br>        generate_and_save_images(generator, epoch + 1, seed)<br>        <br>        print(f&#39;Epoch {epoch+1} completed: Generator Loss = {np.mean(gen_loss_epoch)}, Discriminator Loss = {np.mean(disc_loss_epoch)}&#39;)</pre><p>The <em>train_step</em> function is in charge of carrying out one training iteration for the models of the discriminator and generator. To create artificial images, it first generates a batch of random noise vectors, which are then fed into the generator. Two gradient tapes are made inside the function to record the generator and discriminator’s activities independently. While the discriminator assesses both the created and real images (provided as input), the generator uses the noise as input to produce generated images. Using each model’s unique loss function, the losses are calculated. The optimiser uses the gradients it has computed based on the losses to update the weights of the discriminator and generator, enhancing their performance in the training process.</p><p>The generator’s images during predetermined training epochs can be seen and saved using the <em>generate_and_save_images</em> function. To guarantee consistent output for visualisation, three requirements must be met: the generator model, the current epoch number, and a fixed input (seed) of random noise. From the seed, the program generates images, which are then displayed on a subplot grid. For optimal visualisation, every generated image is resized to its original pixel value range of 0 to 255. The images are then stored to disc with an epoch-number-inclusive filename. This makes it easier to monitor how the generator performs over time as it develops its ability to produce more lifelike images.</p><p>The entire training procedure is coordinated over a predetermined number of epochs by the <em>train </em>function. It initialises lists to hold the discriminator losses and generator for each epoch. It calls the train_step function to execute training on each batch of images from the training dataset as iteratively goes through the batches and logs the losses. It computes the average losses for the epoch after processing each batch and adds them to the corresponding lists for further examination. To see the generator’s output after every epoch and see how the created photos get better over time, the function also calls <em>generate_and_save_images</em>. Lastly, it helps track the training progress by printing the average generator and discriminator losses at the conclusion of each epoch.</p><h4>Generating Images during Training</h4><p>We create and store pictures at the end of every epoch in order to monitor the GAN’s development. Our method creates consistent images for every epoch by using a fixed random noise vector. The Generated image quality improvements can be seen in the following after 100 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceSOrssFeUCmeF1i2ah8Sw.jpeg" /><figcaption>Figure 3: Generated Image quality comparison</figcaption></figure><h3>Conclusion</h3><p>In the end, there is a lot of room for improvements. The generator learns to produce realistic images that closely match the Fashion MNIST data by the end of the training process. The basic ideas of GANs are illustrated in this project, and with minor adjustments, you may use these methods to produce other kinds of data or even better-quality photos.</p><p>And this is how, we generate images using Generative Adversarial Networks, also known as GANs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df5d747812a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Neural Network from Scratch: using ONLY Numpy]]></title>
            <link>https://akashnath29.medium.com/building-a-neural-network-from-scratch-using-numpy-only-653545616eea?source=rss-9941da589fa0------2</link>
            <guid isPermaLink="false">https://medium.com/p/653545616eea</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[diy]]></category>
            <dc:creator><![CDATA[Akash Nath]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 20:31:18 GMT</pubDate>
            <atom:updated>2024-09-19T02:20:42.211Z</atom:updated>
            <content:encoded><![CDATA[<p>Envision imparting human-like handwriting recognition skills to a machine without the need for sophisticated libraries or frameworks. Greetings from the world of pure NumPy, where we will delve into the core of neural networks and create a robust model from scratch for digit recognition. See the wonders of creating a neural network without TensorFlow, PyTorch, or Keras in this blog. We’ll walk you through each step, from setting up the network to optimising its functionality, all the while revealing the complex inner workings. Are you prepared to witness how a few lines of code can convert unprocessed data into insightful forecasts? Fast-forward to the intriguing building and training of neural networks by fastening your seatbelt!</p><h3>Neural Networks</h3><p>A subclass of machine learning algorithms called neural networks is motivated by the composition and operation of the human brain. They are made up of layers of networked nodes, or neurones, each of which processes incoming data and transmits the output to the one above it. These layers use a number of mathematical processes, such as weighted sums and activation functions, to convert the input data into meaningful output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*6mu-WO13nvnNtbXu81bs-w.png" /><figcaption>Figure 1: General Structure of Neural Networks</figcaption></figure><p>Today we will be building a Neural Network from scratch without using Tensorflow or Pytorch library, but we will use ONLY Numpy. I will be creating a handwritten digit recognition network using MNIST CSV dataset by <strong>Dariel Dato-on </strong>on Kaggle, check the dataset out:</p><p><a href="https://www.kaggle.com/datasets/oddrationale/mnist-in-csv">https://www.kaggle.com/datasets/oddrationale/mnist-in-csv</a></p><h4>Requirements:</h4><ol><li>Basic Python</li><li>Basic Numpy</li></ol><p>And you’re good to go!!!</p><p>Building a Neural Network from scratch requires a lot of calculations. But I’ll try to keep the blog as simple as possible.</p><h3>Step 1. Loading Dataset</h3><p>The first step towards building a Neural Network is loading the dataset. We are importing the MNIST dataset — which includes pictures of handwritten numbers — into this block. Every image is represented by a flattened 784-element vector that is a 28x28 pixel grid. The first column of the CSV file contains the labels (digits 0–9), and the other columns include the pixel values.</p><pre>def load_data(train_csv, test_csv):<br>    train_data = pd.read_csv(train_csv)<br>    test_data = pd.read_csv(test_csv)<br>    <br>    X_train = train_data.drop(columns=[&#39;label&#39;]).values / 255.0<br>    y_train = train_data[&#39;label&#39;].values<br>    <br>    X_test = test_data.drop(columns=[&#39;label&#39;]).values / 255.0<br>    y_test = test_data[&#39;label&#39;].values<br>    <br>    return X_train, y_train, X_test, y_test</pre><h3>Step 2. One Hot Encoding Labels</h3><p>We must convert the labels into a one-hot encoded format because we are solving a classification issue with ten potential output classes (digits 0–9). Accordingly, each label will be represented as a vector with 10 elements, with the right class being marked as 1 and the remaining classes as 0.</p><pre>def one_hot_encode(y, num_classes):<br>    return np.eye(num_classes)[y]</pre><h3>Step 3. Defining Activation Functions</h3><p>A neural network that has activation functions can learn and describe complicated patterns in data by introducing non-linearity. Regardless of the number of layers, the network would respond like a linear regression model in the absence of activation functions, which would restrict its capacity to handle increasingly difficult tasks.</p><p>Let’s now examine more closely at the two particular activation functions we employed, Sigmoid and Softmax.</p><h4>Sigmoid</h4><p>Non-linearity is introduced in the hidden layer by the application of the sigmoid function. Regardless of the number of layers in the network, non-linearity is essential because without it, the network would act like a linear model.</p><pre>def sigmoid(z):<br>    return 1 / (1 + np.exp(-z))</pre><h4>Softmax</h4><p>In the output layer, the softmax function is employed to transform raw scores (logits) into probabilities. This is especially helpful when classifying multiple classes.</p><pre>def softmax(z):<br>    exp_z = np.exp(z - np.max(z, axis=1, keepdims=True))<br>    return exp_z / np.sum(exp_z, axis=1, keepdims=True)</pre><h3>Step 4. Building the Network</h3><p>We configure the network’s weights and biases at the initialisation stage, which is crucial for learning. To guarantee diversified learning features and break symmetry, weights (W1 and W2) are initialised with modest random values. By setting the biases (b1 and b2) to zero, the model can modify the activation function without the need for randomisation. The magnitude of weight updates is determined by the learning rate; a value of 0.1 guarantees large adjustments while accounting for the possibility of overshooting. Adequate initialisation is essential for both training and convergence to occur.</p><pre>class NeuralNetwork:<br>    def __init__(self, input_size, hidden_size, output_size, learning_rate=0.1):<br>        self.W1 = np.random.randn(input_size, hidden_size) * 0.01<br>        self.b1 = np.zeros((1, hidden_size))<br>        self.W2 = np.random.randn(hidden_size, output_size) * 0.01<br>        self.b2 = np.zeros((1, output_size))<br>        self.learning_rate = learning_rate</pre><h4>Forward Propagation</h4><p>The neural network processes data during the forward propagation phase in order to produce predictions. Three essential phases are involved in this process: applying activation functions, computing linear combinations, and retrieving the result.</p><pre># Previous code<br><br>def forward(self, X):<br>    self.z1 = np.dot(X, self.W1) + self.b1<br>    self.a1 = sigmoid(self.z1)<br>    self.z2 = np.dot(self.a1, self.W2) + self.b2<br>    self.a2 = softmax(self.z2)<br>    return self.a2</pre><h4>Backward Propagation</h4><p>We calculate the gradients of the loss function with respect to the weights and biases during the backward propagation phase. By using this data, the parameters are changed to reduce loss and raise the accuracy of the model.</p><pre># Previous Code<br><br>def backward(self, X, y_true, y_pred):<br>    m = X.shape[0]<br>        <br>    dz2 = y_pred - y_true<br>    dW2 = np.dot(self.a1.T, dz2) / m<br>    db2 = np.sum(dz2, axis=0, keepdims=True) / m<br><br>    dz1 = np.dot(dz2, self.W2.T) * sigmoid_derivative(self.a1)<br>    dW1 = np.dot(X.T, dz1) / m<br>    db1 = np.sum(dz1, axis=0, keepdims=True) / m<br><br>    self.W1 -= self.learning_rate * dW1<br>    self.b1 -= self.learning_rate * db1<br>    self.W2 -= self.learning_rate * dW2<br>    self.b2 -= self.learning_rate * db2</pre><h4>Training Process</h4><p>In order to reduce the loss function and raise the accuracy of the model, the neural network’s weights and biases are iteratively adjusted during the training phase. The training function is explained in detail below:</p><pre># Previous Code<br><br>def train(self, X, y, epochs=1000):<br>    for epoch in range(epochs):<br>        y_pred = self.forward(X)<br>            <br>        loss = cross_entropy_loss(y, y_pred)<br>            <br>        self.backward(X, y, y_pred)<br>            <br>        if epoch % 100 == 0:<br>            print(f&quot;Epoch {epoch}, Loss: {loss:.4f}&quot;)</pre><h4>Predicion Method</h4><p>Using the trained neural network, the prediction method uses fresh input data to provide class predictions.</p><pre>def predict(self, X):<br>    y_pred = self.forward(X)<br>    return np.argmax(y_pred, axis=1)</pre><h3>Step 5. Implementing the Network and Training Process</h3><p>This section explores the neural network’s training procedure and real-world application. Using NumPy, we will construct a neural network from the ground up, going over all the important parts including backpropagation, forward propagation, and the training loop. These procedures will help us train the network to identify patterns in the data and improve its performance through iterative updates, resulting in a fully functional model that can predict the future with accuracy.</p><h4>Loading Data</h4><p>Firstly we need to load the training and testing data</p><pre>X_train, y_train, X_test, y_test = load_data(&#39;/kaggle/input/mnist-in-csv/mnist_train.csv&#39;, &#39;/kaggle/input/mnist-in-csv/mnist_test.csv&#39;)</pre><h4>One Hot Encoding of Labels</h4><p>The class labels y_train and y_test are transformed into one-hot encoded vectors by the one_hot_encode function.</p><pre>y_train_encoded = one_hot_encode(y_train, 10)<br>y_test_encoded = one_hot_encode(y_test, 10)</pre><h4>Initialization of Parameters</h4><pre>input_size = 784 <br>hidden_size = 64 <br>output_size = 10 <br>learning_rate = 0.1</pre><h4>Network Initialization and Training</h4><p>We will be creating an instance of ‘NeuralNetwork’ class and will train the network based on training data</p><pre>nn = NeuralNetwork(input_size, hidden_size, output_size, learning_rate)<br>nn.train(X_train, y_train_encoded, epochs=1000)<br><br>y_test_pred = nn.predict(X_test)<br>test_accuracy = accuracy(y_test_encoded, one_hot_encode(y_test_pred, 10))<br>print(f&quot;Test Accuracy: {test_accuracy * 100:.2f}%&quot;)</pre><h3>Step 6. Output</h3><p>After training process, the results after each epoch looked something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*_nftqi4oPPE7Ic9WbMwY0w.png" /><figcaption>Figure 2: Training Output</figcaption></figure><p>From 2.3044 at epoch 0 to 0.5552 at epoch 900, the model’s loss clearly decreases, suggesting that learning and convergence were successful over time. An efficient and reliable training procedure is suggested by the loss decreasing steadily without experiencing significant swings. Although there may still be space for improvement, the model generalises to previously unseen data very effectively, as evidenced by the final test accuracy of 87.49%. The model may benefit from additional training or optimisation strategies such early stopping, learning rate tweaking, or regularisation given that the loss keeps going down slightly towards the end. This could increase the model’s convergence speed and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykxhHxxxAyStq3GijBu2Gw.png" /><figcaption>Figure 3: Predicted Outputs</figcaption></figure><p>The picture displays the anticipated results of a handwritten digit recognition model, most likely from the MNIST dataset. The genuine label (genuine) and the expected label (Pred) are shown for every image. There are clear misclassifications even though many forecasts (such as True: 1, Pred: 1 and True: 2, Pred: 2) are accurate. For example, a “9” is mispredicted as a “4”, and a “1” is misinterpreted as a “8.” These mistakes imply that while the model works well overall, it may have trouble with some digits because of identical features or noisy inputs. This suggests that there is still space for improving the accuracy of the model.</p><h4>Loss Graph</h4><p>The network is learning and getting better over time, as seen by the training loss graph’s consistent decline. There isn’t any obvious evidence of overfitting because the loss keeps going down without levelling off, but we can’t be sure of this without a validation loss curve. Although the loss does not appear to be flattening and the network seems to be improving, this could be a sign of underfitting or that the network is not yet fully capturing the patterns in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*UH_qNEeAIu0k2PHyFkyF7g.png" /><figcaption>Figure 4: Loss Graph of the Network</figcaption></figure><p>The whole code is available here:</p><p><a href="https://www.kaggle.com/code/akashnath29/handwritten-digit-recognition-using-numpy">https://www.kaggle.com/code/akashnath29/handwritten-digit-recognition-using-numpy</a></p><p>This blog describes how we used NumPy to create and train a neural network from scratch for digit recognition on the MNIST dataset. With 87.49% test accuracy at the end and a steadily declining loss across training, the model showed good learning. The loss graph indicated a consistent progress without any fluctuations, pointing to a trustworthy training procedure. The odd misclassifications, however, point to areas that could be optimised, including investigating early stopping or modifying learning rates. All things considered, this study sheds light on the possibilities and difficulties of building neural networks from the ground up and provides guidance on machine learning performance tweaking and model enhancement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653545616eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Denoising Autoencoders: What I learnt]]></title>
            <link>https://akashnath29.medium.com/building-denoising-autoencoders-what-i-learnt-fa224cc64a5d?source=rss-9941da589fa0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa224cc64a5d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[denoising-autoencoder]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Akash Nath]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 19:45:48 GMT</pubDate>
            <atom:updated>2024-09-14T19:53:29.265Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine attempting to follow a boisterous pub conversation. Yes, it’s difficult. Imagine a machine now processing complex datasets in the same way. Denoising Autoencoders (DAEs) can help with it.</p><p>These neural networks remove extraneous noise and retrieve the clean signal, much like noise-cancelling headphones do in machine learning. We’ll discuss the operation of DAEs, their practical uses, and the insights I’ve gained from my experience in this blog article. In this article I will share my personal experience with you to make your understandings stronger about autoencoders.</p><h4>Denoising Autoencoders</h4><p>An unique kind of autoencoder called a denoising autoencoder is made specifically to eliminate noise from data. A denoising autoencoder is taught to reconstruct clean data from noisy input, whereas a regular autoencoder just attempts to recover the input. This is accomplished by purposefully introducing noise into the training set of input data, after which the model is trained to retrieve the original data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*ubDFTAaUBooriz5WyzW9Hg.png" /><figcaption>Figure 1: Structure of Autoencoders</figcaption></figure><h4>Process</h4><p>There are a few steps that autoencoders follow to denoise noisy data:</p><p><strong>Add Noise</strong>: The initial stage involves adding noise (such as salt-and-pepper noise, Gaussian noise, etc.) to the input data.</p><p><strong>Encode</strong>: After that, this noisy input is compressed by the encoder into a smaller latent space.</p><p><strong>Decode</strong>: By learning to ignore the noise, the decoder attempts to recreate the original, clean data from the latent representation.</p><h4>Building a Convolutional Autoencoder</h4><p>I’ll guide you through the steps involved in creating a Denoisng Autoencoder (DAE) for picture data in this part. Unsupervised neural networks known as autoencoders are trained to encode input (such as photos) into a representation with fewer dimensions and then decode the data back to its original form. We will concentrate on a convolutional variation in this instance since it can capture spatial hierarchies and is hence very effective for image data. I have used images of size 240px each side as the training and testing data. The following code is the basic structure of the autoencoder:</p><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D<br>from tensorflow.keras.models import Model<br><br>input_img = Input(shape=(240, 240, 3))<br><br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_img)<br>x = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>encoded = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br><br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(encoded)<br>x = UpSampling2D((2, 2))(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>x = UpSampling2D((2, 2))(x)<br>decoded = Conv2D(3, (3, 3), activation=&#39;sigmoid&#39;, padding=&#39;same&#39;)(x)<br><br>autoencoder = Model(input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)<br><br>autoencoder.fit(x_train_noisy, x_train,<br>                          epochs=50,<br>                          batch_size=128,<br>                          shuffle=True,<br>                          validation_data=(x_test_noisy, x_test))</pre><p>Let’s break down more to understand autoencoders properly.</p><p><strong>Input Layer</strong>:</p><p>This denotes the input layer, where 240 x 240 pixel images with three channels (for RGB colour images) are used. These photos will be processed by the autoencoder via its layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*HJf9OovgK_XOR84CHI9_4w.png" /><figcaption>Figure 2: Input Layer of Autoencoders</figcaption></figure><p>Here’s how we define the input layer for autoencoder</p><pre>input_img = Input(shape=(240, 240, 3))</pre><p><strong>Encoder:</strong></p><p>The encoder applies a number of convolutional and pooling layers to compress the input image into a lower-dimensional latent space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*QXxaOKZzSzKfDnj-YMDckg.png" /><figcaption>Figure 3: Encoder Layer of Autoencoders</figcaption></figure><p>Here’s how we make the encoder of Autoencoders</p><pre>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_img)<br>x = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>encoded = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)</pre><p><strong>Bottleneck</strong></p><p>The middle layer of an autoencoder, which compresses the input data into a lower-dimensional latent space, is its bottleneck. By lowering the dimensionality and compelling the network to keep only the most important features while deleting less important data, it performs a critical function. As shown in the output of the second max pooling layer in the provided code, a convolutional autoencoder’s bottleneck is often characterised by reduced spatial dimensions and a compressed feature map. The model’s capacity to learn and rebuild data, striking a balance between compression and detail retention, is impacted by the size of the bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*6wwyckaQ08sGoyiIr6iFXA.png" /><figcaption>Figure 4: Bottleneck of autoencoders</figcaption></figure><p><strong>Decoder:</strong></p><p>Reconstructing the original image from the compressed latent space is the task assigned to the decoder. The original dimensions of the input image are recovered through the use of convolution and upsampling layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*GLK_170oUK71t7kcq5qoOQ.png" /><figcaption>Figure 5: Decoder in Autoencoders</figcaption></figure><p>Here’s how we build the decoder of an Autoencoder</p><pre>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(encoded)<br>x = UpSampling2D((2, 2))(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>x = UpSampling2D((2, 2))(x)</pre><p><strong>Output Layer</strong></p><p>The task of recreating the input data from the compressed latent representation falls to the autoencoder’s output layer. This layer of a convolutional autoencoder upsamples the compressed data back to the original dimensions of the input image using convolutional techniques. For instance, the output layer of the given code uses a final convolutional layer with a sigmoid activation function to generate a picture with pixel values ranging from 0 to 1. By trying to reconstruct the data as closely as possible to the original, the model is able to learn how to precisely restore the compressed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*chpLw83pGuZwpBhEJLxNAw.png" /><figcaption>Figure 6: Output Layer of Autoencoders</figcaption></figure><p>here’s how we build the output layer</p><pre>decoded = Conv2D(3, (3, 3), activation=&#39;sigmoid&#39;, padding=&#39;same&#39;)(x)</pre><h4>Steps to build a Denoising Autoencoder</h4><ol><li>Add noise to original Data: Adding random perturbations, like Gaussian noise, to the clean input images is the process of adding noise to the original data. By feeding noisy images into the model and using this technique, the network is trained to reconstruct the original, noise-free images, denoising autoencoders. Through the simulation of real-world scenarios where data corruption may occur, this method enhances the model’s denoise and imperfection handling capabilities.</li></ol><pre>noise_factor = 0.8<br>x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)<br>x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)<br>x_train_noisy = np.clip(x_train_noisy, 0., 1.)<br>x_test_noisy = np.clip(x_test_noisy, 0., 1.)</pre><p>2. Build the Autoencoder: The very next step is to build the autoencoder. Like I described previously, use Convolutional layers, UpSampling layers and Maxpooling layers to build the autoencoder.</p><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D<br>from tensorflow.keras.models import Model<br><br>input_img = Input(shape=(240, 240, 3))<br><br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_img)<br>x = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>encoded = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br><br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(encoded)<br>x = UpSampling2D((2, 2))(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>x = UpSampling2D((2, 2))(x)<br>decoded = Conv2D(3, (3, 3), activation=&#39;sigmoid&#39;, padding=&#39;same&#39;)(x)<br><br>autoencoder = Model(input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)<br><br>autoencoder.fit(x_train_noisy, x_train,<br>                          epochs=50,<br>                          batch_size=128,<br>                          shuffle=True,<br>                          validation_data=(x_test_noisy, x_test))</pre><p>3. Training the model: The following step contains compiling the model and training it on the noisy data so that it can discriminate between noise and original data.</p><pre>autoencoder = Model(input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)<br><br>history = autoencoder.fit(x_train_noisy, x_train,<br>                          epochs=50,<br>                          batch_size=128,<br>                          shuffle=True,<br>                          validation_data=(x_test_noisy, x_test))</pre><p>4. Testing the model: The last step contains testing the model. We use traditional ‘model.predict()’ on testing data to test the model and get the accuracy</p><pre>decoded_imgs = autoencoder.predict(x_test_noisy)</pre><p>It should return a numpy array of (753, 240, 240, 3) shape.</p><p>We can monitor the training and validation loss graph to understand how the training process was and how the data loss has been reduced gradually in the model training process.</p><pre>import matplotlib.pyplot as plt<br><br>plt.figure(figsize=(10, 5))<br>plt.plot(history.history[&#39;loss&#39;], label=&#39;Training Loss&#39;)<br>plt.plot(history.history[&#39;val_loss&#39;], label=&#39;Validation Loss&#39;)<br>plt.title(&#39;Training and Validation Loss&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*2ciE6PC9PBgt8DFoKKBg8w.png" /><figcaption>Figure 7: Loss Graph</figcaption></figure><p>Based on this graph, we can come to a few decisions:</p><ol><li>Early convergence: The model learns quickly and converges early because both training and validation losses drop off quickly in the first few epochs before stabilising.</li><li>No overfitting: Throughout training, the validation loss closely resembles the training loss, indicating that the model is not overfitting to the training set.</li><li>Plateau reached: Both losses level out and stay steady after roughly 10 epochs, suggesting that additional training might not provide appreciable gains.</li><li>Well-suited generalisation: The model appears to generalise effectively to new data, as evidenced by the final validation loss being extremely near to the training loss.</li><li>Early stopping opportunity: Early halting around epoch 10–15 could conserve computational resources without compromising model performance, given the early convergence and plateau.</li></ol><h4>What Next?</h4><p>Now that the autoencoder model has been successfully trained, you can assess how well it has performed using a variety of measures, including SSIM (Structural Similarity Index) and PSNR (Peak Signal-to-Noise Ratio), which gauge the denoising quality. You might also experiment with different kinds of noise, refine the model, or use the autoencoder for other tasks like feature extraction or anomaly detection. Additionally, think about incorporating the autoencoder into bigger pipelines or projects where clean data is essential for applications that come after.</p><p>In the end, Convolutional Denoising autoencoder construction and training have been incredibly instructive. I now know how to create a network architecture that efficiently splits and reassembles picture data, paying close attention to important parts like the encoder, bottleneck, and decoder. Important insights into data pretreatment and model training were gained by implementing noise addition and watching how the autoencoder learns to denoise data. My grasp of neural network architecture and autoencoder functioning has improved as a result of this project, which also made it clear how crucial it is to experiment with various noise levels and model parameters in order to get the best results. All in all, this practical experience has improved my ability to develop strong machine learning models and equipped me to take on increasingly difficult data processing tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa224cc64a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>