<?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 Mayank D. Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Mayank D. Kulkarni on Medium]]></description>
        <link>https://medium.com/@tech_moonie?source=rss-b2da6a48801a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Mayank D. Kulkarni on Medium</title>
            <link>https://medium.com/@tech_moonie?source=rss-b2da6a48801a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:13:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tech_moonie/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[Unstop Unveiled: How Complexity Algorithms Drive Opportunity Matching]]></title>
            <link>https://medium.com/@tech_moonie/unstop-unveiled-how-complexity-algorithms-drive-opportunity-matching-2f6f16530438?source=rss-b2da6a48801a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f6f16530438</guid>
            <dc:creator><![CDATA[Mayank D. Kulkarni]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 05:27:21 GMT</pubDate>
            <atom:updated>2025-04-21T06:41:56.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0HIpIlZEdFIRSo9TKpDmA.gif" /></figure><p>Ever wondered what drives a platform like Unstop? You know, that site where students and professionals swarm to discover coding challenges, hackathons, internships, and jobs specifically for them? It’s not merely a fancy design or a huge database of opportunities behind the scenes — it’s the smart algorithms whirring in the background. These are not code lines; they’re the pulse of Unstop, making things like lightning-quick searches and on-the-dot opportunity matches seamless. In this 6-minute read, I’ll take you backstage to see how complexity algorithms drive Unstop, demystifying some important concepts and hypothesizing how they’re applied in real-time. Let’s get started!</p><h3>Introduction: The Powerhouse Behind Unstop</h3><p>Unstop is all about matching talent and opportunity. If you’re a coder searching for the next great hackathon or a recruiter advertising open positions, Unstop facilitates with astonishing speed and accuracy. But with millions of users and a deluge of data, how does it remain so effective? Secret sauce is a blend of algorithmic wizardry — imagine time and space complexity, sorting gimmicks, greedy algorithms, and even a sprinkle of randomness. These weapons maintain the platform humming smoothly, even as it gets scaled up.<br>As I don’t have the inside information on Unstop’s precise tech stack, I’ll rely on what I know about comparable platforms and make some informed guesses. We’ll visit two large buckets of algorithmic ideas — simple and sophisticated — and discuss how they could be integrated into Unstop’s tapestry. Ready? Let’s begin.</p><h3>Section I: The Basics That Keep Unstop Snappy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSNE9uL7obd4Zomly_uW1w.png" /></figure><h4>Time and Space Complexity: Efficiency 101</h4><p>Imagine this: you’re digging through a cluttered desk to find a pen. If it’s a small heap, no problem — you’ll see it in a flash. But if it’s a mountain of junk, you’re in for a marathon. That’s time complexity in a nutshell — how long the algorithm will take as the input increases. Then there’s space complexity, or how much memory it devours. For Unstop, both are important. With so many users looking for openings, the site must have algorithms that won’t buckle under strain.<br>We quantify this using asymptotic notations — such fancy words as Big O (worst-case), Big Omega (best-case), and Theta (average-case). Let’s assume Unstop’s search feature takes O(log n) time — that’s logarithmic, so it remains quick even as the data mounts. Contrast that with O(n), where time increases linearly, and you’d notice the slowdown with a large user base. Space-wise, maintaining memory trim prevents servers from crashing when handling millions of profiles.</p><h4>Searching and Sorting: Finding and Ranking Made Easy</h4><p>Ever typed “hackathon” into Unstop’s search bar and gotten instant results? That’s <strong>searching algorithms</strong> at work — likely <strong>binary search</strong>, which cuts the search space in half each step, assuming the data’s sorted. Here’s a quick peek at how it might look:</p><pre>function findOpportunity(opportunities, target):<br>    low = 0<br>    high = length(opportunities) - 1<br>    while low &lt;= high:<br>        mid = (low + high) / 2<br>        if opportunities[mid] == target:<br>            return mid<br>        elif opportunities[mid] &lt; target:<br>            low = mid + 1<br>        else:<br>            high = mid - 1<br>    return &quot;No match found&quot;</pre><p>And sorting? Think of Unstop ranking participants in a coding challenge. Algorithms like <strong>quicksort</strong> or <strong>merge sort</strong> could organize scores or profiles in a snap. These are comparison-based, with a lower bound of O(n log n) — meaning you can’t sort faster without extra tricks.</p><h4>Divide and Conquer: Tackling Big Problems</h4><p>The divide and conquer approach is similar to sharing a huge to-do list between friends. Dissect the problem, solve the fragments, and sew them together again. Binary search is traditional here, but Unstop can also employ merge sort to combine sorted lists of opportunities or quicksort for rapid ranking. When more challenging work — such as finding how many users rank above others (inversions) — is required, this technique excels.<br>Consider order statistics, such as determining the best 10 coders. A randomized algorithm can select a pivot, partition the data, and home in quickly — consider O(n) rather than sorting everything first. Unstop could leverage this to emphasize leaderboard stars without slowing down the system.</p><h4>Dynamic Programming: Smart Optimization</h4><p><strong>Dynamic programming</strong> (DP) is like remembering your shortcuts so you don’t redo work. For simple stuff like Fibonacci numbers, it stores results to avoid recalculating. In Unstop, DP could optimize tougher problems — like the <strong>0–1 knapsack</strong>, figuring out how to pack the most valuable opportunities into a user’s feed under constraints (say, time or skill level). Or maybe the <strong>longest increasing subsequence</strong>, to track a user’s progress through tougher challenges over time.</p><p>Imagine building an <strong>optimal binary search tree</strong> for quick lookups of popular categories like “internships” or “hackathons.” DP ensures Unstop’s searches stay fast and relevant.</p><h3>Section II: Advanced Tricks Up Unstop’s Sleeve</h3><h4>Greedy Strategy: Quick Wins, Big Gains</h4><p>Greedy algorithms take the best choice at each step, hoping it will result in the best overall solution. Consider Huffman coding, encoding data such as user profiles to conserve space, or fractional knapsack, where Unstop may choose to display high-priority opportunities (such as high-paying jobs) over lower-priority ones.</p><p>For user to event matching, a greedy strategy could simulate minimum spanning tree thinking — connecting users to opportunities with minimal “cost” (distance, skill gap, etc.). It is quick and frequently good enough, even though it’s not ideal.</p><h4>Backtracking: Solving the Puzzle</h4><p>Backtracking is similar to attempting every shape in a jigsaw until it is a fit. For the n-queen problem, it tries arrangements and backtracks when it is stuck. In Unstop, this would attempt graph coloring — booking time slots for conflicting events so they do not interfere — or the subset sum problem, selecting challenges that suit a user’s precise skill level.</p><p>Scheduling hackathons? Backtracking could try possibilities until all the restrictions (rooms, time, judges) fit. It’s tedious for large problems, but ideal for smaller, difficult ones.</p><h4>Complexity Classes: Knowing the Limits</h4><p>Here’s where it gets deep. <strong>P</strong> problems are solvable fast — like sorting. <strong>NP</strong> problems? You can check a solution quick (like verifying a schedule works), but finding it might take ages. <strong>NP-complete</strong> problems, like the <strong>traveling salesman</strong> (optimal event tour), are the toughest nuts to crack.</p><p>Unstop’s devs need to know this. If matching users to opportunities perfectly is NP-complete, they won’t waste time chasing an exact answer for millions — they’ll approximate instead.</p><h4>Randomized and Approximation Algorithms: Rolling the Dice</h4><p>Sometimes, you flip a coin to get ahead. <strong>Randomized algorithms</strong> like <strong>Las Vegas</strong> (always correct, time varies) or <strong>Monte Carlo</strong> (fast, might goof) add a twist. <strong>Randomized quicksort</strong> shuffles data to dodge worst-case slowdowns — Unstop might use it for unpredictable user lists.</p><p>For NP-hard stuff, <strong>approximation algorithms</strong> give “close enough” answers fast. Matching users to jobs perfectly? Too slow. But a randomized guess or approximation could nail 90% of it in seconds — good enough for a platform moving at Unstop’s pace.</p><h3>Real-Time Magic: How Unstop Uses These Concepts</h3><p>So, how does Unstop stitch this all together?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZZQmmSdznGbE25ACKN-rQ.png" /></figure><ul><li><strong>Searching and Sorting</strong>: Binary search for instantaneous opportunity lookups; quicksort for ranking challenge leaderboards.</li><li><strong>Divide and Conquer</strong>: Merge sort to blend user data; order statistics to spotlight top talent quickly.</li><li><strong>Dynamic Programming</strong>: Knapsack-style reasoning to craft personalized feeds; OBST for speedy category searches.</li><li><strong>Greedy Strategy</strong>: Huffman to pack data; greedy matching for fast user-opportunity matching.</li><li><strong>Backtracking</strong>: Scheduling events without conflicts, such as graph coloring for time slots.</li><li><strong>Complexity Classes</strong>: Knowing when exact matching is NP-complete and then resorting to approximations.</li><li><strong>Randomized Algorithms</strong>: Shuffling loads between servers or approximating large-data matches.</li></ul><p>Suppose a user is looking for a Python hackathon. Binary search locates it in O(log n) time. DP gathers similar events into their feed. Greedy logic ranks them by relevance. If there are scheduling conflicts that arise, backtracking sorts it out. And if the dataset is gigantic, randomization keeps things going.</p><h3>Wrapping Up: The Algorithmic Edge</h3><p>Unstop is more than a platform — it’s a class in algorithmic optimization. From simple sorting to taming NP-complete monsters, these ideas keep it efficient, intelligent, and easy to use. When you land that ideal job or complete that task on Unstop next time, doff your hat to the algorithms that made it happen. They’re the true MVPs, working quietly behind the scenes to shape your experience, step by step calculation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6f16530438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Imbalanced Data through Regularization]]></title>
            <link>https://medium.com/@tech_moonie/boosting-deep-neural-networks-regularization-techniques-for-imbalanced-data-79a672107e6a?source=rss-b2da6a48801a------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a672107e6a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Mayank D. Kulkarni]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 02:46:37 GMT</pubDate>
            <atom:updated>2024-06-29T10:36:05.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural Networks are inspired by our brain and can learn to recognize handwritten digits. As the name suggests, neural networks have a layered structure that consists of neurons and their network or connection. A neuron in this context is a thing that holds a particular number. In brief, neural networks are the foundation of deep learning and a subfield of machine learning that mimics the human brain to recognize patterns, process data and predict the output. Google’s real-time translation feature is one of the many applications of neural networks.</p><h4>Introduction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-umWomDAFkzsBn0BieAug.jpeg" /><figcaption>Ai Generated Brain Galactic royalty-free stock illustration</figcaption></figure><p>Deep Neural Networks are a subfield of Machine Learning and Artificial Neural Networks. As mentioned before, just like the simple neural networks, DNNs too have many hidden layers between the input and the output layers. The quantity of hidden layers can give you an idea about the depth of the neural network. ANNs are computational models inspired by the human brain. They have various layers of neurons also called nodes between the input and output layers. DNNs play a vital role in various AI and ML areas such as computer vision, game playing, healthcare, natural language processing, etc.</p><p>Machine learning models like DNNs are suitable for large and balanced datasets. However, the real-world data is often imbalanced. The imbalance is caused by bias toward the majority classes and their poor performance on minority classes in a dataset. Some examples of imbalanced datasets are medical diagnosis or fraud detection. Regularization techniques play an important role in preventing the problem of overfitting thus enhancing model performance on imbalanced datasets. Now you might be wondering what overfitting is.</p><p><strong>What is Overfitting?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*GlvA4A2IjzW26ZhNXYwGKA.png" /><figcaption>Graphical plottings of under-fitting, balanced-fitting and over-fitting</figcaption></figure><p>Let me give you a simple example. Suppose you are trying to teach a 4-year-old child to recognize a basic real-world object for instance a ball. You show him/her 10–15 pictures of balls and tell them these are balls. If the child can memorize every detail of these pictures such as color, specific spots, or background, he/she might not recognize balls in some new pictures with a slight difference in features. This represents overfitting.</p><p>In technical terms, overfitting occurs when a machine learning model learns the <strong>training </strong>data too well, including the noise and some random fluctuations in the data. When new or unseen data is fed to the model, it may lead to a decrease in performance. Now that most of the basics have been cleared, let me dive deep into this blog. In this blog, you’ll see:</p><ul><li>The implementation and comparison of L1, L2, and Dropout regularization techniques.</li><li>Exploration of methods to handle imbalanced data such as SMOTE.</li><li>Use of TensorFlow and PyTorch to demonstrate the effectiveness of these techniques.</li></ul><h4>Deep Dive Into Regularization Techniques</h4><p>Regularization is mainly used to solve overfitting. For this, L1, L2, and dropout regularization techniques can be used. Regularization overcomes overfitting by finding an appropriate fit between the underfitting and overfitting plotting. This can be done by shrinking the regression coefficient value.</p><p><strong>L1 Regularization (Lasso Regression): </strong>It<strong> a</strong>dds a penalty that is equal to the absolute value of the magnitude of coefficients. Penalty is an additional term that is added to the loss function of the model, thus preventing overfitting. This leads to sparse models with few coefficients. In L1 regularization, the magnitude of the coefficient can be exactly equal to 0. It can also perform feature selection by ensuring that it selects the variables that hold some magnitude value. The variables whose magnitude is 0 are eliminated.</p><ul><li>Loss function: Loss + λ ∑ |weights| (penalty)</li><li>||W|| = |W1| + |W2| + |W3| + … + |Wn|, where ||W|| = vector of coefficients, |W| = coefficient</li></ul><p>Loss: This tells us how much error there is between what the model thinks and what actually happens. The more the deviation, the more the loss. We add the penalty to compensate for the loss. It also helps to shrink the coefficient magnitude.</p><p><strong>L2 Regularization (Ridge Regression): </strong>In Lasso Regression, there’s a special rule that adds an extra cost based on how big the numbers (coefficients) in the model are. This extra cost is the sum of the absolute values of these numbers. By adding this cost to the model’s loss function, it helps to keep the model from becoming too complex and overfitting the data. Here, the magnitude of the coefficient can be almost but not exactly 0.</p><ul><li>Loss function: Loss + λ ∑ weights² (penalty)</li><li>||W||² = W1² + W2² + W3² + … + Wn², where ||W||² = vector of coefficients, W² = coefficient</li></ul><p><strong>Dropout Regularization:</strong> It drops some amount of neurons from a layer in each iteration of training. Here, dropping out refers to setting the neurons to 0. This allows the model to have more reliance on individual neurons, ensuring strong feature representations. In TensorFlow and PyTorch, Dropout regularization is quite straightforward to implement by specifying the dropout rate.</p><h4>Handling Imbalanced Data</h4><p><strong>SMOTE</strong></p><p>Now, before we get into SMOTE, I want to discuss some terms. The below two concepts help to handle the imbalanced datasets.</p><p><strong>Imagine you’re training a machine to sort socks (the data).</strong> There might be way more black socks (majority class) than colorful ones (minority class). This imbalance can confuse the machine.</p><ul><li><strong>Undersampling:</strong> To help the machine learn from both kinds of socks, you could take out some black socks (reduce the majority class). This way, the machine gets a more even mix of colors to train on. However, throwing away socks might mean losing details about black socks!</li><li><strong>Oversampling:</strong> Instead of throwing socks away, you could make copies of the colorful ones (increase minority class). Now the machine has a bunch of colorful socks to learn from, just like the black ones. One way to do this is by taking a colorful sock and slightly changing its shade (SMOTE — Synthetic Minority Over-sampling Technique). This creates new “fake” colorful socks that the machine can learn from without losing information about the original colorful ones.</li></ul><p>Both undersampling and oversampling aim to create a more balanced sock pile (dataset) for the machine to learn from effectively. What it does is create fake minority class samples so that they match the majority class. Firstly, SMOTE identifies the minority samples in the dataset that need oversampling. It then selects k nearest neighbors for each minority class. It can be calculated using the Euclidean distance formula. Then, SMOTE generates new synthetic samples by inserting between the features of the selected minority class sample and its k nearest neighbors. The new synthetic samples are added to the dataset, increasing the representation of the minority class and thus balancing the class distribution. This increases the overall performance and accuracy of the model.</p><h4>Experiment Setup</h4><p><strong>Dataset Selection: </strong>I used the <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud">Credit Card Fraud Detection dataset</a> from Kaggle. From my research on Kaggle, I learned that it is very imbalanced making it a great choice for our experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h24zytpgEZ8VhaWgakYr0A.png" /><figcaption>Credit card fraud detection dataset from Kaggle</figcaption></figure><p><strong>IDE Selection: </strong>I used <a href="https://jupyter.org/install">Jupyter Notebook</a> for this project because it was already set up on my computer. You can also perform this experiment on <a href="https://colab.research.google.com/">Google Colab</a>. It already contains the setup for TensorFlow and PyTorch. Moreover, it contains free GPU resources as well!</p><p><strong>Evaluation Metrics:</strong> The metrics that are sensitive to class imbalance namely:</p><ul><li><strong>Precision:</strong> It is the ratio of correctly predicted positive observations to the total predicted positives. It is also called Positive Predictive Value. For example, in a spam email detector, most of the emails stated as spam are indeed spam if the precision is high.</li><li><strong>Recall:</strong> It is the ratio of correctly predicted positive observations to all the observations in the class. It is also called Sensitivity. For example, in a medical test for a disease, if the recall is high, then most of the patients are identified with the disease correctly.</li><li><strong>F1 Score:</strong> Think of it like a report card grade for a detective trying to catch a thief (positive class). The detective wants to be right on two things: catching the thief (high recall) and not accusing innocent people (high precision). The F1 Score combines these two ideas into one grade. It’s especially useful when there’s an uneven situation, like having way more innocent people around (negative class) than actual thieves. So, a good F1 Score means the detective is good at both catching the thief and avoiding mistakes, even with a crowd of innocent people around.</li><li><strong>ROC Curve:</strong> This is like a visual game strategy for your guessing game. It shows how likely you are to accidentally pick a dog when you meant to pick a cat (false positive rate) as you get better at picking actual cats (true positive rate). It helps you see the trade-off between being careful (not picking dogs as cats) and being bold (catching more cats).</li><li><strong>AUC Curve:</strong> This is a single score that sums up how good your overall guessing game strategy is based on the ROC Curve. A high AUC means you’re a master guesser, hardly ever mixing up cats and dogs. For example, if you’re sorting through emails to identify spam (positive class), a high AUC means your system is excellent at separating real emails from spammy ones.</li></ul><h4>Implementation in TensorFlow and PyTorch</h4><p><strong>Implementation in TensorFlow:</strong></p><p><strong>Step 1: </strong>Import the necessary libraries and download the dataset so that you can use it through your computer’s local path in your experiment. You can directly link it as well, as it is available online.</p><pre>import tensorflow as tf  # Import TensorFlow for machine learning tasks<br>from sklearn.model_selection import train_test_split  # Import function to split data<br>from sklearn.preprocessing import StandardScaler  # Import function for data scaling<br>from sklearn.metrics import classification_report, roc_auc_score  # Import functions for model evaluation<br>from imblearn.over_sampling import SMOTE  # Import function for handling imbalanced data<br>import pandas as pd  # Import Pandas for data manipulation<br><br># Here, you need to use the dataset from a file named &quot;creditcard.csv&quot; on your computer<br>data = pd.read_csv(&quot;creditcard.csv&quot;)</pre><p><strong>Step 2:</strong> I used SMOTE here. This helps us catch any sneaky patterns without getting fooled by the uneven information.</p><pre><br>X = data.drop(&#39;Class&#39;, axis=1)<br>y = data[&#39;Class&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)<br><br>smote = SMOTE(random_state=42)<br>X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)</pre><p><strong>Step 3: </strong>The third step implements the Dropout and L2 regularization on the model. I have also trained the models on the SMOTE-balanced dataset.</p><pre>#Dropout regularized model build and compile<br>dropout_model = tf.keras.Sequential([<br>    tf.keras.layers.Input(shape=(X_train.shape[1],)),  # Define input shape here<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>    tf.keras.layers.Dropout(0.5),<br>    tf.keras.layers.Dense(32, activation=&#39;relu&#39;),<br>    tf.keras.layers.Dropout(0.5),<br>    tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br>dropout_model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br>#L2 regularized model build and compile<br>l2_model = tf.keras.Sequential([<br>    tf.keras.layers.Input(shape=(X_train.shape[1],)),  # Define input shape here<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;, kernel_regularizer=tf.keras.regularizers.l2(0.01)),<br>    tf.keras.layers.Dense(32, activation=&#39;relu&#39;, kernel_regularizer=tf.keras.regularizers.l2(0.01)),<br>    tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br>l2_model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br>#Training the Dropout model<br>print(&quot;Training Dropout Regularized Model...&quot;)<br>dropout_model.fit(X_train_smote, y_train_smote, epochs=20, batch_size=64, validation_data=(X_test, y_test))<br><br>#Training the L2 regularized model<br>print(&quot;Training L2 Regularized Model...&quot;)<br>l2_model.fit(X_train_smote, y_train_smote, epochs=20, batch_size=64, validation_data=(X_test, y_test))</pre><p><strong>Step 4: </strong>This step evaluates the model performance using precision, recall, F1 score, and ROC-AUC.</p><pre>#Evaluation of Dropout Model<br>print(&quot;Dropout Model Evaluation:&quot;)<br>y_pred_dropout = (dropout_model.predict(X_test) &gt; 0.5).astype(int)<br>print(classification_report(y_test, y_pred_dropout))<br>print(f&quot;ROC-AUC: {roc_auc_score(y_test, y_pred_dropout)}&quot;)<br><br>#Evaluation of L2 Regularized Model<br>print(&quot;L2 Regularized Model Evaluation:&quot;)<br>y_pred_l2 = (l2_model.predict(X_test) &gt; 0.5).astype(int)<br>print(classification_report(y_test, y_pred_l2))<br>print(f&quot;ROC-AUC: {roc_auc_score(y_test, y_pred_l2)}&quot;)</pre><p><strong>Implementation in PyTorch:</strong></p><p>As I mentioned earlier, the same steps are required to implement a program through pytorch as that of tensorflow. Firstly, you need to import libraries and load the dataset. You need to ensure that the data is in tensor format. Then define the models with dropout and L2 regularization using the ‘nn’ module of pytorch. I then train the models and monitor the loss. And finally, evaluate the models using classification metrics.</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br><br>#Data in tensor format<br>X_train_smote_tensor = torch.tensor(X_train_smote, dtype=torch.float32)<br>y_train_smote_tensor = torch.tensor(y_train_smote, dtype=torch.float32).view(-1, 1)<br>X_test_tensor = torch.tensor(X_test, dtype=torch.float32)<br>y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)<br><br>#Dropout model definition<br>class DropoutModel(nn.Module):<br>    def __init__(self):<br>        super(DropoutModel, self).__init__()<br>        self.fc1 = nn.Linear(X_train_smote.shape[1], 64)<br>        self.dropout = nn.Dropout(0.5)<br>        self.fc2 = nn.Linear(64, 32)<br>        self.fc3 = nn.Linear(32, 1)<br><br>    def forward(self, x):<br>        x = torch.relu(self.fc1(x))<br>        x = self.dropout(x)<br>        x = torch.relu(self.fc2(x))<br>        x = self.dropout(x)<br>        x = torch.sigmoid(self.fc3(x))<br>        return x<br><br>#L2 regularization model definition<br>class L2Model(nn.Module):<br>    def __init__(self):<br>        super(L2Model, self).__init__()<br>        self.fc1 = nn.Linear(X_train_smote.shape[1], 64)<br>        self.fc2 = nn.Linear(64, 32)<br>        self.fc3 = nn.Linear(32, 1)<br><br>    def forward(self, x):<br>        x = torch.relu(self.fc1(x))<br>        x = torch.relu(self.fc2(x))<br>        x = torch.sigmoid(self.fc3(x))<br>        return x<br><br>dropout_model_pytorch = DropoutModel()<br>l2_model_pytorch = L2Model()<br>criterion = nn.BCELoss()<br>dropout_optimizer = optim.Adam(dropout_model_pytorch.parameters(), lr=0.001)<br>l2_optimizer = optim.Adam(l2_model_pytorch.parameters(), lr=0.001, weight_decay=0.01)<br><br>#Training function<br>def train_model(model, optimizer, epochs=20):<br>    for epoch in range(epochs):<br>        model.train()<br>        optimizer.zero_grad()<br>        outputs = model(X_train_smote_tensor)<br>        loss = criterion(outputs, y_train_smote_tensor)<br>        loss.backward()<br>        optimizer.step()<br>        if epoch % 5 == 0:<br>            print(f&#39;Epoch {epoch}/{epochs}, Loss: {loss.item()}&#39;)<br><br>#Training the Dropout Model<br>print(&quot;Training Dropout Model...&quot;)<br>train_model(dropout_model_pytorch, dropout_optimizer)<br><br>#Training the L2 Regularized Model<br>print(&quot;Training L2 Regularized Model...&quot;)<br>train_model(l2_model_pytorch, l2_optimizer)<br><br>#Evaluation of both the models<br>def evaluate_model(model):<br>    model.eval()<br>    with torch.no_grad():<br>        outputs = model(X_test_tensor)<br>        predicted = (outputs &gt; 0.5).float()<br>        print(classification_report(y_test_tensor, predicted))<br>        print(f&quot;ROC-AUC: {roc_auc_score(y_test_tensor, predicted)}&quot;)<br><br>print(&quot;Dropout Model Evaluation:&quot;)<br>evaluate_model(dropout_model_pytorch)<br><br>print(&quot;L2 Regularized Model Evaluation:&quot;)<br>evaluate_model(l2_model_pytorch)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuoB3XwPFk43WQH27qFkrg.png" /><figcaption>Dropout and L2 Regularization model evaluation using TensorFlow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*ZWfYkM85CHd73yC5rZLulA.png" /><figcaption>Dropout and L2 Regularization model evaluation using PyTorch</figcaption></figure><h4>Visualizing the Performance of TensorFlow and PyTorch models using L1, L2, and Dropout Regularization Methods</h4><p>The below program visualizes the training performance of L1, L2, and Dropout regularization methods over multiple epochs and compares them in terms of loss and accuracy.</p><pre>#Importing matplotlib and numpy libraries<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>epochs = np.arange(1, 21)<br><br>#The actual output loss values received from the trained tensorflow model<br>tensorflow_dropout_loss = [<br>    0.1277, 0.0209, 0.0143, 0.0131, 0.0121, 0.0114, 0.0100, 0.0105, <br>    0.0099, 0.0095, 0.0089, 0.0096, 0.0087, 0.0085, 0.0089, 0.0082, <br>    0.0085, 0.0080, 0.0080, 0.0083<br>]<br>tensorflow_l2_loss = [<br>    0.2197, 0.0718, 0.0584, 0.0517, 0.0486, 0.0449, 0.0428, 0.0412, <br>    0.0396, 0.0391, 0.0374, 0.0360, 0.0351, 0.0343, 0.0345, 0.0341, <br>    0.0337, 0.0331, 0.0325, 0.0327<br>]<br><br>#Placeholder for L1 regularization<br>tensorflow_l1_loss = np.zeros(20)<br><br>#The actual output loss values received from the trained pytorch model<br>pytorch_dropout_loss = [<br>    0.7339675426483154, 0.6843622922897339, 0.6445250511169434, 0.6133188009262085, <br>    0.5895711183547974, 0.5716317296028137, 0.5584596991539001, 0.5481079816818237, <br>    0.5395382642745972, 0.5324133634567261, 0.5262507796287537, 0.5208789110183716, <br>    0.5160691142082214, 0.5116611123085022, 0.5074766278266907, 0.5034264922142029, <br>    0.4993727207183838, 0.4953068792819977, 0.4912206828594208, 0.4871104657649994<br>]<br>pytorch_l2_loss = [<br>    0.6651896238327026, 0.6205797791481018, 0.588776707649231, 0.5653122663497925, <br>    0.5484013557434082, 0.5358819961547852, 0.5268221497535706, 0.5195815563201904, <br>    0.5136638283729553, 0.5087372660636902, 0.5045480728149414, 0.5009095668792725, <br>    0.4976845979690552, 0.4947664737701416, 0.4920711815357208, 0.48953330516815186, <br>    0.4871104657649994, 0.48477473855018616, 0.4825062155723572, 0.4802912473678589<br>]<br><br>#Placeholder for L1 regularization<br>pytorch_l1_loss = np.zeros(20)<br><br>#The actual output accuracy values received from the trained tensorflow model<br>tensorflow_dropout_acc = [<br>    0.9954, 0.9979, 0.9981, 0.9986, 0.9986, 0.9989, 0.9988, 0.9985, <br>    0.9987, 0.9987, 0.9986, 0.9988, 0.9988, 0.9989, 0.9988, 0.9989, <br>    0.9990, 0.9990, 0.9991, 0.9990<br>]<br>tensorflow_l2_acc = [<br>    0.9899, 0.9870, 0.9918, 0.9871, 0.9948, 0.9884, 0.9923, 0.9952, <br>    0.9918, 0.9908, 0.9938, 0.9927, 0.9955, 0.9942, 0.9938, 0.9941, <br>    0.9963, 0.9956, 0.9950, 0.9936<br>]<br><br>#Placeholder for L1 accuracy<br>tensorflow_l1_acc = np.zeros(20)<br><br>#The actual output accuracy values received from the trained pytorch model<br>pytorch_dropout_acc = [<br>    0.689, 0.720, 0.740, 0.754, 0.764, 0.771, 0.777, 0.782, 0.786, <br>    0.789, 0.792, 0.794, 0.796, 0.798, 0.799, 0.801, 0.802, 0.803, <br>    0.804, 0.805<br>]<br>pytorch_l2_acc = [<br>    0.643, 0.684, 0.705, 0.720, 0.731, 0.739, 0.746, 0.751, 0.756, <br>    0.760, 0.763, 0.766, 0.769, 0.771, 0.774, 0.776, 0.778, 0.779, <br>    0.781, 0.783<br>]<br><br>#Placeholder for L1 accuracy<br>pytorch_l1_acc = np.zeros(20)<br><br>#Plotting Training Loss<br>plt.figure(figsize=(12, 6))<br>plt.subplot(1, 2, 1)<br>plt.plot(epochs, tensorflow_dropout_loss, label=&#39;TF Dropout&#39;, linestyle=&#39;-&#39;)<br>plt.plot(epochs, tensorflow_l2_loss, label=&#39;TF L2&#39;, linestyle=&#39;--&#39;)<br>plt.plot(epochs, tensorflow_l1_loss, label=&#39;TF L1&#39;, linestyle=&#39;:&#39;)<br>plt.plot(epochs, pytorch_dropout_loss, label=&#39;PT Dropout&#39;, linestyle=&#39;-&#39;)<br>plt.plot(epochs, pytorch_l2_loss, label=&#39;PT L2&#39;, linestyle=&#39;--&#39;)<br>plt.plot(epochs, pytorch_l1_loss, label=&#39;PT L1&#39;, linestyle=&#39;:&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.title(&#39;Training Loss&#39;)<br>plt.legend()<br>plt.grid(True)<br><br>#Plotting Training Accuracy<br>plt.subplot(1, 2, 2)<br>plt.plot(epochs, tensorflow_dropout_acc, label=&#39;TF Dropout&#39;, linestyle=&#39;-&#39;)<br>plt.plot(epochs, tensorflow_l2_acc, label=&#39;TF L2&#39;, linestyle=&#39;--&#39;)<br>plt.plot(epochs, tensorflow_l1_acc, label=&#39;TF L1&#39;, linestyle=&#39;:&#39;)<br>plt.plot(epochs, pytorch_dropout_acc, label=&#39;PT Dropout&#39;, linestyle=&#39;-&#39;)<br>plt.plot(epochs, pytorch_l2_acc, label=&#39;PT L2&#39;, linestyle=&#39;--&#39;)<br>plt.plot(epochs, pytorch_l1_acc, label=&#39;PT L1&#39;, linestyle=&#39;:&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.title(&#39;Training Accuracy&#39;)<br>plt.legend()<br>plt.grid(True)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjfPHS-61sFE0e2mheF4jg.png" /><figcaption>Training loss and Training accuracy for L1, L2, and Dropout methods using TensorFlow and PyTorch</figcaption></figure><p><strong>Observations:</strong> The above plots depict that:</p><ul><li>The TensorFlow models with L2 and Dropout Regularization have a better performance in terms of both accuracy as well as loss.</li><li>The PyTorch models perform rather poorly as compared to TensorFlow models with higher loss and lower accuracy.</li></ul><p>The below program visualizes and compares the performance of the TensorFlow and PyTorch models using Precision-Recall curves and ROC using L2 and Dropout regularization techniques. These curves help in understanding the concession between different types of errors.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.metrics import roc_curve, precision_recall_curve, auc<br><br>y_true = y_test<br><br>#Predictions from TensorFlow output<br>y_pred_dropout_tf = dropout_model.predict(X_test).flatten()<br>y_pred_l2_tf = l2_model.predict(X_test).flatten()<br><br>#Predictions from PyTorch output<br>y_pred_dropout_pt = dropout_model_pytorch(X_test_tensor).detach().numpy().flatten()<br>y_pred_l2_pt = l2_model_pytorch(X_test_tensor).detach().numpy().flatten()<br><br>#ROC Curves<br>plt.figure(figsize=(12, 6))<br><br>plt.subplot(1, 2, 1)<br>fpr_tf_d, tpr_tf_d, _ = roc_curve(y_true, y_pred_dropout_tf)<br>fpr_tf_l2, tpr_tf_l2, _ = roc_curve(y_true, y_pred_l2_tf)<br>fpr_pt_d, tpr_pt_d, _ = roc_curve(y_true, y_pred_dropout_pt)<br>fpr_pt_l2, tpr_pt_l2, _ = roc_curve(y_true, y_pred_l2_pt)<br><br>plt.plot(fpr_tf_d, tpr_tf_d, label=&#39;TF Dropout (AUC = {:.2f})&#39;.format(auc(fpr_tf_d, tpr_tf_d)))<br>plt.plot(fpr_tf_l2, tpr_tf_l2, label=&#39;TF L2 (AUC = {:.2f})&#39;.format(auc(fpr_tf_l2, tpr_tf_l2)))<br>plt.plot(fpr_pt_d, tpr_pt_d, label=&#39;PT Dropout (AUC = {:.2f})&#39;.format(auc(fpr_pt_d, tpr_pt_d)))<br>plt.plot(fpr_pt_l2, tpr_pt_l2, label=&#39;PT L2 (AUC = {:.2f})&#39;.format(auc(fpr_pt_l2, tpr_pt_l2)))<br><br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.title(&#39;ROC Curves&#39;)<br>plt.legend()<br>plt.grid(True)<br><br>#Precision-Recall Curves<br>plt.subplot(1, 2, 2)<br>prec_tf_d, recall_tf_d, _ = precision_recall_curve(y_true, y_pred_dropout_tf)<br>prec_tf_l2, recall_tf_l2, _ = precision_recall_curve(y_true, y_pred_l2_tf)<br>prec_pt_d, recall_pt_d, _ = precision_recall_curve(y_true, y_pred_dropout_pt)<br>prec_pt_l2, recall_pt_l2, _ = precision_recall_curve(y_true, y_pred_l2_pt)<br><br>plt.plot(recall_tf_d, prec_tf_d, label=&#39;TF Dropout&#39;)<br>plt.plot(recall_tf_l2, prec_tf_l2, label=&#39;TF L2&#39;)<br>plt.plot(recall_pt_d, prec_pt_d, label=&#39;PT Dropout&#39;)<br>plt.plot(recall_pt_l2, prec_pt_l2, label=&#39;PT L2&#39;)<br><br>plt.xlabel(&#39;Recall&#39;)<br>plt.ylabel(&#39;Precision&#39;)<br>plt.title(&#39;Precision-Recall Curves&#39;)<br>plt.legend()<br>plt.grid(True)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQ65Ae12c6N_q52MToX3sg.png" /><figcaption>Evaluation of TensorFlow and PyTorch models of L2 and Dropout Regularization using ROC and Precision-Recall Curves</figcaption></figure><p><strong>Observations:</strong> The above plots depict that:</p><ul><li>ROC Curves: Mostly, all the models have high AUC values suggesting that they can very well distinguish the positive and negative classes with TensorFlow having L2 regularization having the highest AUC value (0.97). Other models also perform well which means that both regularization techniques are proving to be effective.</li><li>Precision-Recall Curves: The ‘success charts’ (Precision-Recall Curves) show more up-and-down trends compared to the other charts (ROC Curves). This suggests the models are more sensitive to different parts of the data. Interestingly, the ‘TensorFlow with L2’ approach seems to perform well consistently, even edging out the other methods here.</li></ul><p>Overall, all models are showing decent performance with TensorFlow with L2 regularization having a slight edge in performance. The choice between the frameworks (TensorFlow and PyTorch), as well as the regularization methods (L2 and Dropout), depends on specific requirements of precision, recall, and the type of application.</p><h4>Conclusion</h4><p>In this blog, I have delved into the critical task of regularization in neural networks across frameworks like TensorFlow and PyTorch. By exploring different regularization techniques like L1, L2, and Dropout regularization, you can understand how we can overcome overfitting and handle imbalanced datasets using SMOTE.</p><p>Thank you for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a672107e6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>