<?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 Abhinav Mishra on Medium]]></title>
        <description><![CDATA[Stories by Abhinav Mishra on Medium]]></description>
        <link>https://medium.com/@abhinav.mishra123?source=rss-238f414ffd02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZiLi8l5pIh0umH7pS-oOAw.jpeg</url>
            <title>Stories by Abhinav Mishra on Medium</title>
            <link>https://medium.com/@abhinav.mishra123?source=rss-238f414ffd02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:59:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhinav.mishra123/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[PyTorch vs TensorFlow: A Clear Comparison for Deep Learning Enthusiasts]]></title>
            <link>https://medium.com/@abhinav.mishra123/pytorch-vs-tensorflow-a-clear-comparison-for-deep-learning-enthusiasts-03058af73697?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/03058af73697</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 01:02:22 GMT</pubDate>
            <atom:updated>2024-09-25T01:02:22.003Z</atom:updated>
            <content:encoded><![CDATA[<p>As a machine learning practitioner, you’ve probably come across both <strong>PyTorch</strong> and <strong>TensorFlow</strong>. These two frameworks are among the most widely used in the deep learning community. Both are powerful, but they have different strengths and features that might make one more suitable than the other, depending on the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQ7xyF9UiZAVsF-A" /></figure><p>In this post, I’ll break down the main differences between PyTorch and TensorFlow to help you better understand which might be a better fit for your needs.</p><h3>1. Dynamic vs Static Computation Graphs</h3><p>The key distinction between PyTorch and TensorFlow lies in how they build and execute computation graphs.</p><ul><li><strong>PyTorch</strong> uses a <em>dynamic computation graph</em>. This means the graph is built on-the-fly during runtime, making it more intuitive to debug and change while writing code. It feels more like writing normal Python code and is very flexible for quick experimentation.</li><li><strong>TensorFlow</strong>, on the other hand, traditionally used a <em>static computation graph</em> (before TensorFlow 2.0). The graph is defined and compiled beforehand, and then executed. This makes TensorFlow optimized for large-scale deployments, but it’s less flexible when you want to make changes during runtime. However, with <strong>TensorFlow 2.0</strong>, eager execution is introduced, which allows TensorFlow to behave more like PyTorch in this regard, supporting dynamic graphs.</li></ul><p><strong>When to choose PyTorch:</strong><br>If you value flexibility and quick experimentation, PyTorch’s dynamic graph is a great choice.</p><p><strong>When to choose TensorFlow:</strong><br>TensorFlow shines in production-level applications where performance and scalability are key, especially when you need to deploy a model.</p><h3>2. Community and Ecosystem</h3><p>Both frameworks have large communities and robust ecosystems, but the focus and tooling can differ.</p><ul><li><strong>TensorFlow</strong> has a massive ecosystem with tools like <strong>TensorFlow Extended (TFX)</strong> for production, <strong>TensorFlow Lite</strong> for mobile and IoT deployment, and <strong>TensorFlow Serving</strong> for model deployment at scale. It is well-suited for industrial applications where you need to go beyond just model training to include deployment and scaling.</li><li><strong>PyTorch</strong> has been widely adopted in research settings due to its simplicity and ease of use. Libraries like <strong>Hugging Face Transformers</strong> and <strong>fastai</strong> are built on top of PyTorch, offering pre-trained models and high-level APIs that make development faster and easier.</li></ul><p><strong>When to choose PyTorch:</strong><br>If you’re in research or want to focus on model prototyping with ease, PyTorch’s research-friendly ecosystem is ideal.</p><p><strong>When to choose TensorFlow:</strong><br>For end-to-end solutions, TensorFlow’s production tools are unmatched. If your focus is on building scalable systems, TensorFlow’s ecosystem will help you.</p><h3>3. Model Deployment</h3><p>TensorFlow has an edge when it comes to <strong>model deployment</strong>.</p><ul><li><strong>TensorFlow</strong> provides <strong>TensorFlow Serving</strong>, a flexible and efficient system for serving machine learning models in production environments. It also supports exporting models to <strong>TensorFlow Lite</strong> for mobile devices and <strong>TensorFlow.js</strong> for web applications.</li><li><strong>PyTorch</strong>, though more popular in research, has made strides in deployment with tools like <strong>TorchServe</strong> (a model serving library developed in collaboration with AWS) and <strong>PyTorch Mobile</strong> for mobile deployments. However, the deployment ecosystem around PyTorch isn’t as mature as TensorFlow’s.</li></ul><p><strong>When to choose PyTorch:</strong><br>If you’re looking to deploy in smaller-scale or custom settings, PyTorch works well. For instance, it’s a good choice if you’re building applications with cloud providers like AWS using TorchServe.</p><p><strong>When to choose TensorFlow:</strong><br>For large-scale or enterprise-level deployment, TensorFlow’s established serving systems and tools make it the superior option.</p><h3>4. APIs and Ease of Use</h3><ul><li><strong>PyTorch</strong> has an intuitive and Pythonic API. If you’re familiar with Python, you’ll find PyTorch’s API natural and straightforward. This makes it easier to get started, especially for those with a software engineering background.</li><li><strong>TensorFlow</strong> has historically had a steeper learning curve, especially with its older static graph approach. However, TensorFlow 2.0 brought in <strong>Keras</strong> as the official high-level API, making it much more user-friendly. TensorFlow now offers a simpler API experience while retaining its powerful features.</li></ul><p><strong>When to choose PyTorch:</strong><br>If you prioritize simplicity, PyTorch will feel more intuitive, especially for those familiar with Python.</p><p><strong>When to choose TensorFlow:</strong><br>With TensorFlow 2.0’s improvements, the API has become easier, but PyTorch still edges ahead in user experience. However, if you want more built-in functionalities, TensorFlow’s API is worth considering.</p><h3>5. Performance</h3><p>When it comes to <strong>performance</strong>, both frameworks are highly optimized for deep learning tasks, but they do have some differences.</p><ul><li><strong>TensorFlow</strong> often performs better for large-scale production environments, especially with the use of its <strong>XLA (Accelerated Linear Algebra)</strong> compiler that optimizes computations for improved performance on hardware like GPUs and TPUs.</li><li><strong>PyTorch</strong> is known for being easy to work with and has also seen improvements in performance optimization, but it might not match TensorFlow when it comes to very large-scale or enterprise-level optimizations.</li></ul><p><strong>When to choose PyTorch:</strong><br>For most research-level or small-scale tasks, PyTorch’s performance is more than adequate.</p><p><strong>When to choose TensorFlow:</strong><br>If you need cutting-edge optimizations and scalability for industrial-scale applications, TensorFlow might give you an edge.</p><h3>Conclusion: Which One Should You Use?</h3><ul><li><strong>Choose PyTorch</strong> if you’re doing research, working in academia, or need a framework that’s easy to use, experiment with, and debug.</li><li><strong>Choose TensorFlow</strong> if you’re working on large-scale production systems, need end-to-end tools for deployment, or are focused on scaling models efficiently.</li></ul><p>Both frameworks are rapidly evolving, so your choice will depend on the specific requirements of your project. In recent years, the gap between them has narrowed significantly, and it’s not uncommon to see organizations using both, depending on the task at hand.</p><p>Let me know in the comments which framework you prefer and why!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03058af73697" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bidirectional LSTM for MNIST Classification using PyTorch]]></title>
            <link>https://medium.com/@abhinav.mishra123/bidirectional-lstm-for-mnist-classification-using-pytorch-8583780647e5?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/8583780647e5</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 18:40:22 GMT</pubDate>
            <atom:updated>2024-09-13T18:40:22.607Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll dive into how to implement a Bidirectional LSTM (Long Short-Term Memory) model using PyTorch. LSTMs are a type of Recurrent Neural Network (RNN) known for their ability to capture long-term dependencies in sequential data, making them great for time-series and NLP tasks. A Bidirectional LSTM, in particular, enhances the model’s performance by processing the input data in both forward and backward directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PFAE3x-IoGqFdyKh" /></figure><p>We’ll be applying this model to the MNIST dataset, a popular dataset for image classification tasks, to see how well a Bidirectional LSTM can classify handwritten digits.</p><h3>Imports and Setup</h3><p>Let’s first import the necessary libraries:</p><blockquote>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torch.utils.data import DataLoader<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms</blockquote><h3>What is a Bidirectional LSTM?</h3><p>A Bidirectional LSTM (BRNN) processes the data in both forward and reverse directions. This helps capture patterns that might be missed when the input is only read in one direction. We’ll create a BRNN that reads image data as sequential input rows, treating each row as a step in the sequence.</p><h3>Creating the Bidirectional LSTM Model</h3><p>Here’s the BRNN class, which is where we define our model architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*hdAFmlPtln8SF2wzVxTQAQ.png" /></figure><ul><li><strong>Input Size</strong>: 28 (since each MNIST image is 28x28 pixels)</li><li><strong>Hidden Size</strong>: Number of neurons in each LSTM layer.</li><li><strong>Num Layers</strong>: We are using 2 layers of LSTMs.</li><li><strong>Bidirectional</strong>: True, so the model reads the data forward and backward.</li></ul><h3>Setting the Device</h3><p>To leverage GPU, we check if CUDA is available:</p><blockquote>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</blockquote><h3>Defining Hyperparameters</h3><p>Next, let’s define the hyperparameters:</p><p>input_size = 28<br>sequence_length = 28<br>num_layers = 2<br>hidden_size = 256<br>num_classes = 10<br>learning_rate = 0.001<br>batch_size = 64<br>num_epochs = 2<br>Loading the MNIST Data</p><p>We use the PyTorch DataLoader to load the MNIST dataset for training and testing:</p><blockquote>train_dataset = datasets.MNIST(root=’dataset/’, train=True, transform=transforms.ToTensor(), download=True)<br>train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)</blockquote><blockquote>test_dataset = datasets.MNIST(root=’dataset/’, train=False, transform=transforms.ToTensor(), download=True)<br>test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)</blockquote><h3>Initializing the Network</h3><p>Here we instantiate the BRNN model and send it to the available device:</p><p>model = BRNN(input_size, hidden_size, num_layers, num_classes).to(device)</p><h3>Loss and Optimizer</h3><p>We define the loss function using Cross-Entropy Loss and the optimizer as Adam:</p><blockquote>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.parameters(), lr=learning_rate)</blockquote><h3>Training the Network</h3><p>Now, we train the model for the defined number of epochs. The training loop involves a forward pass, loss computation, backward pass, and optimizer step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*9qZt7YwkRnovaEr7Pey78g.png" /></figure><ul><li><strong>Forward Pass</strong>: Compute the output using the model.</li><li><strong>Backward Pass</strong>: Calculate gradients and update the model parameters.</li></ul><h3>Checking Accuracy</h3><p>Once the training is complete, we define a function to evaluate the model’s accuracy on both the training and test datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*m7iX4S0pqFq8E2ruF-1iZQ.png" /></figure><h3>Results</h3><p>After training the Bidirectional LSTM for just 2 epochs, here’s the model’s performance:</p><p><strong>Checking accuracy on training data<br>Got 58506 / 60000 correct with accuracy 97.51%</strong></p><p><strong>Checking accuracy on test data<br>Got 9732 / 10000 correct with accuracy 97.32%</strong></p><p>s you can see, the model performs well on the MNIST dataset, achieving over 97% accuracy.</p><h3>Conclusion</h3><p>Using a Bidirectional LSTM, we’ve been able to classify the MNIST dataset with impressive accuracy. While LSTMs are typically used for sequential data like text, they can also be applied to image data when treated as sequences. Bidirectional LSTMs take this further by learning from both directions, improving the model’s understanding of patterns.</p><p>This implementation can be a great starting point for more complex tasks, especially in scenarios where sequence order is essential. Feel free to experiment with more layers, larger datasets, and additional techniques like regularization to improve performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8583780647e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transfer Learning: Leveraging Pre-trained Models for MNIST Classification]]></title>
            <link>https://medium.com/@abhinav.mishra123/understanding-transfer-learning-leveraging-pre-trained-models-for-mnist-classification-e7caa07e4bb5?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7caa07e4bb5</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 17:20:40 GMT</pubDate>
            <atom:updated>2024-09-13T17:20:40.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Transfer learning is a powerful technique in deep learning that allows us to reuse pre-trained models for tasks they weren’t originally designed for. This approach can save time and computational resources, while often achieving excellent results by leveraging knowledge from previous training. In this post, we’ll go through how to apply transfer learning using a pre-trained ResNet18 model for MNIST digit classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTWY6OQArvTkmwg_" /></figure><h3>1. Problem Overview</h3><p>MNIST is a simple dataset containing images of handwritten digits (0–9) in grayscale. The task is to classify these images into their respective digit categories. Although we could train a custom model from scratch, transfer learning allows us to use a model that has already been trained on a large dataset (like ImageNet) to improve our results with minimal additional training.</p><h3>2. Setting Up the Model</h3><p>First, let’s walk through the code for setting up our transfer learning model using PyTorch.</p><blockquote>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.utils.data import DataLoader<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms<br>import torchvision.models as models</blockquote><p>We begin by importing necessary libraries and functions. We’ll be using a pre-trained ResNet18 model and modifying it to handle grayscale images (since MNIST images have only 1 channel, while ImageNet images have 3).</p><h3>3. Defining Hyperparameters and Device</h3><p>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</p><p>in_channel = 1<br>num_classes = 10<br>learning_rate = 0.001<br>batch_size = 64<br>num_epochs = 5</p><p>These are our hyperparameters: num_classes is set to 10 because MNIST has 10 digit categories, and num_epochs is 5 for simplicity.</p><h3>4. Pre-trained ResNet18 Model Modification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*mNfZlyI4Dk29dFcuKA0kFg.png" /></figure><p>Here’s what’s happening:</p><ul><li>We load a pre-trained ResNet18 model, which was originally designed for 3-channel images.</li><li>The first convolutional layer is modified to accept 1-channel images, allowing us to process the grayscale MNIST images.</li><li>We freeze the pre-trained parameters so that only the final fully connected layer will be trained. This helps retain the knowledge from the original model while focusing on classifying MNIST digits.</li></ul><h3>5. Loading Data</h3><blockquote>train_dataset = datasets.MNIST(root=’dataset/’, train=True, transform=transforms.ToTensor(), download=True)<br>train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)</blockquote><blockquote>test_dataset = datasets.MNIST(root=’dataset/’, train=False, transform=transforms.ToTensor(), download=True)<br>test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)</blockquote><p>We load the MNIST dataset using PyTorch’s datasets module. The dataset is transformed into tensors so they can be processed by the model.</p><h3>6. Training the Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*2bs17dEytDjkUF8r8PTuBw.png" /></figure><p>We define the loss function as CrossEntropyLoss and the optimizer as Adam. The model is trained for 5 epochs.</p><h3>7. Checking Accuracy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*EYpXizeCZZwX8n0gs2Ml3g.png" /></figure><p>This function calculates the model’s accuracy by counting the correct predictions out of the total samples. We check the accuracy on both the training and test data.</p><h3>8. Results</h3><p>Checking accuracy on training data<br>Got 36586 / 60000 with accuracy 60.98%<br>Checking accuracy on test data<br>Got 6081 / 10000 with accuracy 60.81%</p><p>After training, the model achieves around <strong>60% accuracy</strong> on both the training and test datasets. While this accuracy may not be impressive for MNIST, it’s important to note that we trained only the final layer with minimal effort, leveraging the pre-trained knowledge from ResNet18.</p><h3>9. Conclusion</h3><p>In this tutorial, we used transfer learning to classify the MNIST dataset with a pre-trained ResNet18 model. By modifying the model’s input layer and freezing pre-trained parameters, we were able to achieve decent results without having to train the entire network from scratch.</p><p>The power of transfer learning lies in its ability to apply knowledge gained from one task to another, making it a valuable tool for many applications in deep learning.</p><p>Feel free to try this approach with different datasets or experiment with fine-tuning more layers to see how it affects performance!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7caa07e4bb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Recurrent Neural Network (RNN) with PyTorch]]></title>
            <link>https://medium.com/@abhinav.mishra123/building-a-recurrent-neural-network-rnn-with-pytorch-9358a696d7dc?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/9358a696d7dc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 18:28:23 GMT</pubDate>
            <atom:updated>2024-09-12T18:28:23.634Z</atom:updated>
            <content:encoded><![CDATA[<p>Recurrent Neural Networks (RNNs) are widely used for sequence data tasks such as time series forecasting, language modeling, and more. In this post, I will walk you through how to build and train an RNN using PyTorch based on the MNIST dataset, which consists of handwritten digit images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C-UjzYPNLbrfA8Y5" /></figure><h3>Imports</h3><p>First, let’s import the necessary libraries:</p><blockquote>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torch.utils.data import DataLoader<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms</blockquote><p>These imports include PyTorch’s core libraries, optimization functions, and the MNIST dataset from torchvision.</p><h3>Creating the RNN Model</h3><p>We’ll define a class RNN, which inherits from nn.Module. The model will use a GRU (Gated Recurrent Unit), a type of RNN, to process sequence data. We also include a fully connected layer to output the final classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*nB-1zlKG_i9YVhwCxzdaqg.png" /></figure><ul><li><strong>GRU</strong>: We use a GRU layer for handling the sequential nature of the data.</li><li><strong>Forward Function</strong>: This is where the data flows through the network. The hidden state is initialized, passed into the GRU, and then flattened for the fully connected layer.</li></ul><h3>Setting the Device</h3><p>We set up the device to run on a GPU if available:</p><blockquote>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</blockquote><h3>Model Hyperparameters</h3><p>Next, we define some key parameters:</p><blockquote>input_size = 28<br>sequence_length = 28<br>num_layers = 2<br>hidden_size = 256<br>num_classes = 10<br>learning_rate = 0.001<br>batch_size = 64<br>num_epochs = 2</blockquote><ul><li><strong>input_size</strong> and <strong>sequence_length</strong>: MNIST images are 28x28, and we treat the rows as a sequence of 28 inputs.</li><li><strong>hidden_size</strong>: The number of units in the GRU’s hidden layer.</li><li><strong>num_layers</strong>: Number of GRU layers.</li><li><strong>num_classes</strong>: For MNIST, there are 10 digit classes (0–9).</li><li><strong>learning_rate</strong>, <strong>batch_size</strong>, and <strong>num_epochs</strong> are common training hyperparameters.</li></ul><h3>Loading the Dataset</h3><p>We use the MNIST dataset for training and testing. PyTorch’s DataLoader helps load and batch the data.</p><blockquote>train_dataset = datasets.MNIST(root=’dataset/’, train=True, transform=transforms.ToTensor(), download=True)<br>train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)</blockquote><blockquote>test_dataset = datasets.MNIST(root=’dataset/’, train=False, transform=transforms.ToTensor(), download=True)<br>test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)</blockquote><h3>Initializing the Model</h3><p>With the RNN class defined, we instantiate the model:</p><blockquote>model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)</blockquote><h3>Loss Function and Optimizer</h3><p>For this classification task, we use cross-entropy loss and the Adam optimizer:</p><blockquote>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.parameters(), lr=learning_rate)</blockquote><h3>Training the RNN</h3><p>We now train the model. For each batch, we feed the data into the model, compute the loss, and update the weights through backpropagation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*u9XLMs_KEvR7E1nVwRFYRA.png" /></figure><ul><li><strong>squeeze(1)</strong>: This removes the unnecessary channel dimension from the MNIST images.</li><li><strong>optimizer.step()</strong>: This applies the gradient descent step to update the weights.</li></ul><h3>Checking Accuracy</h3><p>After training, we check the model’s accuracy on both the training and test data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*7iAkhCwTMoj_r1zLq6sfDA.png" /></figure><p>This function evaluates the model on the given data loader. It switches the model to evaluation mode and calculates the accuracy by comparing predictions with actual labels.</p><h3>Results</h3><p>After training for just 2 epochs, the model achieves impressive results:</p><blockquote>Checking accuracy on training data<br>Got 59060 / 60000 correct with accuracy 98.43%<br>Checking accuracy on test data<br>Got 9827 / 10000 correct with accuracy 98.27%</blockquote><p>This shows that even a simple RNN with GRU layers can achieve high accuracy on the MNIST dataset.</p><h3>Conclusion</h3><p>In this post, we’ve built an RNN using PyTorch to classify images from the MNIST dataset. By using a GRU, we can effectively handle sequence data, and the model performs very well, achieving over 98% accuracy on the test set. With more training or model tuning, this accuracy could potentially be improved even further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9358a696d7dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding a Simple CNN using PyTorch: Step-by-Step Guide]]></title>
            <link>https://medium.com/@abhinav.mishra123/understanding-a-simple-cnn-using-pytorch-step-by-step-guide-f12bdf834a10?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/f12bdf834a10</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 15:19:28 GMT</pubDate>
            <atom:updated>2024-09-12T15:19:28.906Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I will walk you through how I built and trained a simple Convolutional Neural Network (CNN) in PyTorch. I’ll explain every part of the code, from importing the required libraries to training and testing the model. This is a great way to understand how CNNs work for beginners in deep learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sB_Vs07yKkZm5wEp" /></figure><h3>Step 1: Importing the Required Libraries</h3><p>Before we begin, let’s import the necessary libraries. Each of these serves a specific purpose for building, training, and testing our model.</p><blockquote>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torch.utils.data import DataLoader<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms</blockquote><ul><li><strong>torch</strong>: Main PyTorch library.</li><li><strong>nn</strong>: Used to define neural network layers.</li><li><strong>optim</strong>: Provides optimization algorithms like Adam, used for training.</li><li><strong>DataLoader</strong>: Loads the data in batches.</li><li><strong>datasets</strong>: Contains popular datasets like MNIST.</li><li><strong>transforms</strong>: Used for data preprocessing (e.g., converting data into tensors).</li></ul><h3>Step 2: Building the Simple CNN</h3><p>A CNN is designed to handle image data effectively. Below is a simple CNN architecture that consists of two convolutional layers followed by a fully connected (FC) layer for classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*CddwMvO1e4gqZ21yNV42Ag.png" /></figure><p><strong>Explanation:</strong></p><ul><li><strong>conv1</strong>: First convolutional layer. It takes in 1 channel (grayscale images), outputs 8 channels, and uses a 3x3 kernel.</li><li><strong>pool</strong>: Max pooling layer reduces the spatial dimensions by 2x (downsampling).</li><li><strong>conv2</strong>: Second convolutional layer. It takes in 8 channels and outputs 16 channels, again with a 3x3 kernel.</li><li><strong>fc1</strong>: Fully connected layer for classification. The input is flattened before being passed through this layer.</li><li><strong>ReLU</strong>: Activation function applied after each convolution for non-linearity.</li></ul><h3>Step 3: Setting the Device</h3><p>We ensure that our code runs on the GPU if it’s available, otherwise, it defaults to the CPU.</p><blockquote>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</blockquote><h3>Step 4: Defining Hyperparameters</h3><p>Hyperparameters control the model’s training process. Here’s a quick explanation of each:</p><blockquote>in_channel = 1 # Input is grayscale, hence 1 channel.<br>num_classes = 10 # MNIST has 10 output classes (digits 0–9).<br>learning_rate = 0.001 # Step size for optimization.<br>batch_size = 64 # Number of images passed through the network at once.<br>num_epochs = 5 # Number of times the entire dataset passes through the network.</blockquote><h3>Step 5: Loading the MNIST Dataset</h3><p>The MNIST dataset consists of 60,000 training and 10,000 test images of handwritten digits. Each image is 28x28 pixels in grayscale.</p><blockquote>train_dataset = datasets.MNIST(root=’dataset/’, train=True, transform=transforms.ToTensor(), download=True)<br>train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)</blockquote><blockquote>test_dataset = datasets.MNIST(root=’dataset/’, train=False, transform=transforms.ToTensor(), download=True)<br>test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)</blockquote><p><strong>Explanation:</strong></p><ul><li><strong>train_dataset/test_dataset</strong>: Loads the MNIST data.</li><li><strong>transforms.ToTensor()</strong>: Converts images to tensors, which are the format PyTorch models accept.</li><li><strong>DataLoader</strong>: Splits the dataset into batches to train the model efficiently.</li></ul><h3>Step 6: Initializing the Network</h3><p>Now we instantiate the CNN and move it to the device (GPU or CPU).</p><blockquote>model = CNN().to(device)</blockquote><h3>Step 7: Loss Function and Optimizer</h3><p>To train the model, we need a loss function to minimize and an optimizer to adjust the weights. Here, I use cross-entropy loss, which is suitable for classification tasks, and the Adam optimizer, which is a popular choice for training neural networks.</p><blockquote>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.parameters(), lr=learning_rate)</blockquote><h3>Step 8: Training the CNN</h3><p>We train the CNN by looping through the dataset multiple times (epochs). In each epoch, we forward the data through the network, compute the loss, and perform backpropagation to update the model’s weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*VuEPAx74ux6lXGO3uoUmYA.png" /></figure><ul><li><strong>data</strong> and <strong>targets</strong>: Mini-batches of images and their labels.</li><li><strong>loss.backward()</strong>: Calculates the gradients using backpropagation.</li><li><strong>optimizer.step()</strong>: Adjusts the model parameters (weights).</li></ul><h3>Step 9: Checking Accuracy</h3><p>After training, we evaluate the model’s performance on both the training and test data to check how well it learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*BeKo7u4eAljplKgI52BWOw.png" /></figure><p><strong>Explanation:</strong></p><ul><li><strong>model.eval()</strong>: Puts the model in evaluation mode, so it doesn’t update the weights.</li><li><strong>torch.no_grad()</strong>: Disables gradient computation during inference.</li><li><strong>predictions == y</strong>: Compares the predictions with the true labels.</li></ul><h3>Output</h3><p>Here’s what the model’s performance looks like:</p><blockquote>Checking accuracy on training data Got 59196 / 60000 with accuracy 98.66 Checking accuracy on test data Got 9829 / 10000 with accuracy 98.29</blockquote><p>The CNN achieved around 98% accuracy on both the training and test sets, which is quite good for a simple model like this.</p><h3>Conclusion</h3><p>In this post, I showed you how to build a simple CNN from scratch using PyTorch to classify handwritten digits from the MNIST dataset. We covered everything from data loading, model building, and training to evaluating the model’s performance. CNNs are powerful tools for image classification tasks, and this example is a stepping stone to understanding more complex architectures in deep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f12bdf834a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding a Simple Neural Network with PyTorch]]></title>
            <link>https://medium.com/@abhinav.mishra123/understanding-a-simple-neural-network-with-pytorch-0a61691b083a?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a61691b083a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 16:48:37 GMT</pubDate>
            <atom:updated>2024-09-11T16:48:37.633Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll break down a simple neural network implemented using PyTorch. We’ll go through the code, explain what each part does, and show how it all fits together to classify images from the MNIST dataset (a set of 28x28 grayscale images of handwritten digits).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uJIdEm2fA-PNGvwg" /></figure><p>Let’s dive into the basics and make sure you leave with a clear understanding of each step!</p><h3>1. Imports: Setting Up the Environment</h3><p>We begin by importing the required libraries from PyTorch:</p><blockquote>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torch.utils.data import DataLoader<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms</blockquote><ul><li>torch is PyTorch’s main library.</li><li>torch.nn contains all neural network modules.</li><li>torch.optim provides optimizers like Adam and SGD to update model weights.</li><li>datasets contains various datasets like MNIST.</li><li>transforms helps us preprocess the data (like converting images to tensors).</li></ul><h3>2. Creating the Neural Network</h3><p>Our neural network is a simple fully connected network. It’s called a “fully connected” network because each neuron in one layer is connected to every neuron in the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*0ti_yRJGlD1XZo0L40Nncg.png" /></figure><ul><li>fc1 connects the input to the hidden layer. We use 784 inputs (since each MNIST image is 28x28 = 784 pixels) and 50 neurons in the hidden layer.</li><li>fc2 connects the hidden layer to the output layer, which has 10 neurons (for 10 classes, one for each digit from 0 to 9).</li><li>ReLU is an activation function that helps the network learn complex patterns by introducing non-linearity.</li></ul><h3>3. Setting the Device</h3><p>Next, we check if a GPU is available and use it if possible. If not, we default to using the CPU.</p><blockquote>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</blockquote><h3>4. Hyperparameters</h3><p>Hyperparameters are values we set before training that control how the network learns:</p><blockquote>input_size = 784<br>num_classes = 10<br>learning_rate = 0.001<br>batch_size = 64<br>num_epochs = 1</blockquote><ul><li>input_size: Each image is 28x28 pixels, so the total number of inputs is 784.</li><li>num_classes: We have 10 possible digit classes (0-9).</li><li>learning_rate: Controls how big the steps are when updating weights during training.</li><li>batch_size: The number of samples processed before the model&#39;s weights are updated.</li><li>num_epochs: The number of times the entire dataset is passed through the network.</li></ul><h3>5. Loading the Data</h3><p>We use PyTorch’s datasets to load the MNIST dataset. The dataset is automatically downloaded if it doesn&#39;t already exist.</p><blockquote>train_dataset = datasets.MNIST(root=’dataset/’, train=True, transform=transforms.ToTensor(), download=True)<br>train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)</blockquote><blockquote>test_dataset = datasets.MNIST(root=’dataset/’, train=False, transform=transforms.ToTensor(), download=True)<br>test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)</blockquote><ul><li>We load both the training and test datasets.</li><li>ToTensor() converts the images into tensors (PyTorch&#39;s way of handling data).</li></ul><h3>6. Initializing the Network</h3><p>We create an instance of our neural network and send it to the device (GPU or CPU).</p><blockquote>model = NN(input_size=input_size, num_classes=num_classes).to(device)</blockquote><h3>7. Loss Function and Optimizer</h3><p>We define the loss function (which tells us how far off our predictions are) and the optimizer (which updates the weights).</p><blockquote>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.parameters(), lr=learning_rate)</blockquote><ul><li>CrossEntropyLoss is great for classification problems.</li><li>Adam is an optimizer that adjusts the weights based on the gradients.</li></ul><h3>8. Training the Network</h3><p>Now we train the network by passing the data through the network, calculating the loss, and updating the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*XZY3sU4ZNBZMmn9XH_yHPA.png" /></figure><ul><li>We loop through each batch of data.</li><li>reshape converts each image into a 1D vector of 784 elements.</li><li>forward computes the predictions.</li><li>loss.backward calculates the gradients.</li><li>optimizer.step updates the weights.</li></ul><h3>9. Checking Accuracy</h3><p>After training, we check how well the model performs on both the training and test datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*LGJFqF0NwStIJtgADP2NDg.png" /></figure><ul><li>We check how many predictions match the actual labels.</li><li>model.eval() switches the model to evaluation mode (no training here).</li><li>torch.no_grad() ensures that gradients aren&#39;t calculated during this step.</li></ul><h3>10. Results</h3><p>After running the code, you should see something like this:</p><blockquote>Checking accuracy on training data<br>Got 55858 / 60000 with accuracy 93.10<br>Checking accuracy on test data<br>Got 9302 / 10000 with accuracy 93.02</blockquote><p>The network achieves about 93% accuracy, which is pretty good for such a simple model!</p><h3>Conclusion</h3><p>This post walked through the code to build and train a simple neural network using PyTorch. Although it’s a basic model, it gives you a solid foundation to start working with neural networks. You can experiment by adding more layers, changing activation functions, or using different datasets.</p><p>Feel free to play around with the hyperparameters to see how the model’s performance changes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a61691b083a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Steps into PyTorch: Understanding Tensors]]></title>
            <link>https://medium.com/@abhinav.mishra123/my-first-steps-into-pytorch-understanding-tensors-f5fa59234497?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5fa59234497</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 16:29:16 GMT</pubDate>
            <atom:updated>2024-09-10T16:29:16.162Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I took my first steps into PyTorch, focusing on some key fundamentals of working with tensors. Tensors are central to PyTorch and play a similar role to arrays in NumPy but are more powerful, especially with GPU acceleration. Below is what I covered today:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MH2H-DYmAMiW3wdD" /></figure><h3>1. Initializing a Tensor</h3><p>I started by learning how to create a tensor in PyTorch. PyTorch provides several ways to initialize tensors:</p><ul><li>torch.empty(size)</li><li>torch.zeros(size)</li><li>torch.ones(size)</li><li>torch.rand(size)</li></ul><p>These methods create tensors filled with random values, zeros, ones, or uniformly distributed random values, respectively.</p><p>Example: import torch # Creating tensors empty_tensor = torch.empty(3, 3) zeros_tensor = torch.zeros(3, 3) ones_tensor = torch.ones(3, 3) rand_tensor = torch.rand(3, 3) print(rand_tensor)</p><h3>2. Common Tensor Initialization Methods</h3><p>I explored other useful tensor creation methods:</p><ul><li><strong>torch.eye(n)</strong>: Creates an identity matrix</li><li><strong>torch.arange(start, end, step)</strong>: Creates a tensor with a range of values</li><li><strong>torch.linspace(start, end, steps)</strong>: Creates a tensor with evenly spaced numbers</li></ul><h3>3. Initializing and Converting Tensors to Different Types</h3><p>Converting tensors to different data types is simple with PyTorch. I tried converting between integer, float, and double types:</p><p>float_tensor = torch.tensor([1.2, 3.4]) int_tensor = float_tensor.int() # Convert to int double_tensor = float_tensor.double() # Convert to double print(int_tensor, double_tensor)</p><p>The ability to switch between types is useful depending on whether you need precision (float/double) or simplicity (int).</p><h3>4. Converting Arrays to Tensors and Vice-Versa</h3><p>PyTorch allows for easy conversion between NumPy arrays and tensors:</p><p>import numpy as np # Numpy array to tensor np_array = np.array([1, 2, 3]) tensor_from_array = torch.from_numpy(np_array) # Tensor to numpy array tensor_to_np = tensor_from_array.numpy() print(tensor_from_array, tensor_to_np)</p><p>This compatibility makes it easy to work between the two libraries without losing data or precision.</p><h3>5. Tensor Math &amp; Comparison Operations</h3><p>I also explored the math operations and comparisons PyTorch offers:</p><p>x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5, 6]) # Arithmetic operations sum_tensor = x + y prod_tensor = x * y # Comparison operations greater_than = x &gt; y equal = x == y print(sum_tensor, prod_tensor, greater_than, equal)</p><p>These operations work element-wise, similar to NumPy arrays, but are highly optimized for deep learning workflows.</p><h3>6. Tensor Indexing</h3><p>Indexing and slicing tensors is straightforward and works like NumPy arrays:</p><p>tensor = torch.tensor([[1, 2], [3, 4], [5, 6]]) # Indexing elements print(tensor[0, 1]) # Access second element in the first row # Slicing tensors print(tensor[:, 1]) # Access second column</p><p>This allows for extracting specific parts of the tensor easily.</p><h3>7. Tensor Reshaping</h3><p>Finally, I experimented with reshaping tensors, which is key when working with neural networks:</p><p>tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) reshaped_tensor = tensor.view(3, 2) print(reshaped_tensor)</p><p>Reshaping is often required when preparing data for a model or manipulating its dimensions.</p><h3>Conclusion</h3><p>This was a productive start, and I’m excited to dig deeper into PyTorch. Mastering tensors will be the foundation for everything that follows, from building neural networks to performing more advanced operations.</p><p>Stay tuned for more insights as I continue my PyTorch journey!</p><p>print(rand_tensor)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5fa59234497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 5 of My SQL Journey: ALTER, MODIFY, TRUNCATE, and All Types of Joins]]></title>
            <link>https://medium.com/@abhinav.mishra123/day-5-of-my-sql-journey-alter-modify-truncate-and-all-types-of-joins-bd2f98de26b7?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd2f98de26b7</guid>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 21:37:31 GMT</pubDate>
            <atom:updated>2024-08-22T21:37:31.036Z</atom:updated>
            <content:encoded><![CDATA[<p>On the fifth day of my SQL learning journey, I dived into some crucial commands and concepts that are essential for managing and manipulating database structures and relationships. Today, I focused on the ALTER and MODIFY commands, the TRUNCATE command, and the various types of joins available in SQL. Here&#39;s a summary of what I learned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JKuiYKLCef_S81Tv.jpg" /></figure><h3>ALTER and MODIFY Commands</h3><h3>ALTER Command</h3><p>The ALTER command is used to add, delete, or modify columns in an existing table. It allows you to change the structure of your database tables without having to delete them.</p><p>Adding a Column: ALTER TABLE employees DROP COLUMN phone_number;</p><h3>MODIFY Command</h3><p>The MODIFY command is used within the ALTER command to change the data type or size of an existing column.</p><p><strong>Modifying a Column: </strong>ALTER TABLE employees MODIFY COLUMN salary DECIMAL(15, 2);</p><p>This command changes the salary column to a DECIMAL type with 15 digits in total and 2 decimal places.</p><h3>TRUNCATE Command</h3><p>The TRUNCATE command is used to delete all rows from a table, but unlike DELETE, it does not log individual row deletions. It is faster and uses fewer system resources, but it is less flexible because it cannot be rolled back in some systems.</p><p><strong>Truncating a Table: </strong>TRUNCATE TABLE employees;</p><p>This command removes all rows from the employees table, leaving the table structure intact but empty.</p><h3>Types of Joins</h3><p>Joins are used to combine rows from two or more tables based on a related column. Here are the different types of joins:</p><h3>INNER JOIN</h3><p>The INNER JOIN returns only the rows that have matching values in both tables.</p><p>Example: SELECT employees.name, orders.order_id FROM employees INNER JOIN orders ON employees.id = orders.employee_id;</p><p>This command retrieves the names of employees and their respective order IDs where there is a match between the employee ID and the order’s employee ID.</p><h3>LEFT JOIN (or LEFT OUTER JOIN)</h3><p>The LEFT JOIN returns all the rows from the left table and the matched rows from the right table. If there is no match, NULL values are returned for columns from the right table.</p><p>Example: SELECT employees.name, orders.order_id FROM employees LEFT JOIN orders ON employees.id = orders.employee_id;</p><p>This command retrieves all employee names and their respective order IDs, including employees who haven’t placed any orders (with NULL for the order ID).</p><h3>RIGHT JOIN (or RIGHT OUTER JOIN)</h3><p>The RIGHT JOIN is the opposite of the LEFT JOIN. It returns all the rows from the right table and the matched rows from the left table.</p><p>Example: SELECT employees.name, orders.order_id FROM employees RIGHT JOIN orders ON employees.id = orders.employee_id;</p><p>This command retrieves all order IDs and their respective employee names, including orders that haven’t been assigned to any employee (with NULL for the employee name).</p><h3>FULL JOIN (or FULL OUTER JOIN)</h3><p>The FULL JOIN returns all rows when there is a match in either left or right table. If there is no match, NULL values are returned for columns from the table without a match.</p><p>Example: SELECT employees.name, orders.order_id FROM employees FULL JOIN orders ON employees.id = orders.employee_id;</p><p>This command retrieves all employees and all orders, matching them where possible, and using NULL where there is no match.</p><h3>CROSS JOIN</h3><p>The CROSS JOIN returns the Cartesian product of the two tables, which means it will combine every row of the first table with every row of the second table.</p><p>Example: SELECT employees.name, orders.order_id FROM employees CROSS JOIN orders;</p><p>This command combines each employee with each order, which can result in a large number of rows.</p><h3>Putting It All Together</h3><p>Here’s an example that combines these concepts:</p><p>ALTER TABLE employees ADD COLUMN phone_number VARCHAR(15); ALTER TABLE employees MODIFY COLUMN salary DECIMAL(15, 2); TRUNCATE TABLE old_records; SELECT employees.name, orders.order_id FROM employees LEFT JOIN orders ON employees.id = orders.employee_id;</p><p>In this example:</p><ol><li>A phone_number column is added to the employees table.</li><li>The salary column is modified to have a specific decimal format.</li><li>The old_records table is truncated, removing all its data.</li><li>A LEFT JOIN is performed to retrieve all employees and their associated order IDs.</li></ol><h3>Reflections</h3><p>Today’s session covered a lot of ground, from altering table structures to understanding how to efficiently join tables. Each command and join type adds another tool to my SQL toolkit, making data management more efficient and flexible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd2f98de26b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 4 of My SQL Journey: HAVING Clause, UPDATE Command, DELETE Command, and Cascading Foreign Keys]]></title>
            <link>https://medium.com/@abhinav.mishra123/day-4-of-my-sql-journey-having-clause-update-command-delete-command-and-cascading-foreign-keys-ff8e82efba98?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8e82efba98</guid>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 20:16:29 GMT</pubDate>
            <atom:updated>2024-08-12T20:16:29.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*z0gdbEE1ibEYzTd6.jpg" /></figure><p>On the fourth day of my SQL learning journey, I explored more advanced concepts, including the HAVING clause, the UPDATE command, the DELETE command, and cascading foreign keys. These are powerful tools for managing and manipulating data in a database. Here’s what I learned:</p><h3>HAVING Clause</h3><p>The HAVING clause is used to filter groups after applying the GROUP BY clause. It is similar to the WHERE clause, but HAVING works on aggregated data.</p><p>Example:SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department HAVING AVG(salary) &gt; 50000;</p><p>This command retrieves departments where the average salary is greater than $50,000.</p><h3>UPDATE Command</h3><p>The UPDATE command is used to modify existing records in a table. You can update one or multiple columns simultaneously.</p><p>Example: UPDATE employees SET salary = salary * 1.10 WHERE department = &#39;Sales&#39;;</p><p>This command increases the salary of all employees in the Sales department by 10%.</p><h3>DELETE Command</h3><p>The DELETE command is used to remove records from a table. You can specify conditions to delete specific rows.</p><p>Example: DELETE FROM employees WHERE age &lt; 25;</p><p>This command deletes all employees who are younger than 25 years old.</p><h3>Cascading Foreign Keys</h3><p>Cascading foreign keys allow you to maintain referential integrity between related tables. When a record in the parent table is updated or deleted, cascading actions can be set to automatically update or delete the corresponding records in the child table.</p><h3>ON DELETE CASCADE</h3><p>This action deletes the related records in the child table when the corresponding record in the parent table is deleted.</p><p>Example: CREATE TABLE orders ( order_id INT PRIMARY KEY, employee_id INT, FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE CASCADE );</p><h3>ON UPDATE CASCADE</h3><p>This action updates the related records in the child table when the corresponding record in the parent table is updated.</p><p>Example: CREATE TABLE orders ( order_id INT PRIMARY KEY, employee_id INT, FOREIGN KEY (employee_id) REFERENCES employees(id) ON UPDATE CASCADE );</p><h3>Putting It All Together</h3><p>Here’s an example that combines these concepts:</p><p>UPDATE employees SET salary = salary * 1.10 WHERE department = &#39;Sales&#39;; DELETE FROM employees WHERE age &lt; 25; SELECT department, COUNT(*) AS num_employees FROM employees GROUP BY department HAVING COUNT(*) &gt; 5;</p><p>In this example:</p><ol><li>Salaries of Sales department employees are increased by 10%.</li><li>Employees younger than 25 are deleted from the database.</li><li>Departments with more than 5 employees are selected.</li></ol><h3>Reflections</h3><p>Today’s session added more depth to my SQL knowledge. The HAVING clause, cascading foreign keys, and the ability to update and delete records are essential tools for any SQL user. I’m excited to continue building on these skills as I move forward in my learning journey.</p><p>Feel free to share any tips or resources if you’re also learning SQL. Let’s keep the momentum going and master SQL together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8e82efba98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3 of My SQL Journey: Operators, LIMIT, ORDER BY, Aggregate Functions, and GROUP BY]]></title>
            <link>https://medium.com/@abhinav.mishra123/day-3-of-my-sql-journey-operators-limit-order-by-aggregate-functions-and-group-by-9556096c951b?source=rss-238f414ffd02------2</link>
            <guid isPermaLink="false">https://medium.com/p/9556096c951b</guid>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abhinav Mishra]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 20:37:34 GMT</pubDate>
            <atom:updated>2024-08-07T20:37:34.024Z</atom:updated>
            <content:encoded><![CDATA[<p>Today marks the third day of my SQL learning journey. I delved into several important aspects of SQL: operators, the LIMIT clause, the ORDER BY clause, aggregate functions, and the GROUP BY clause. Here’s what I learned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cKKb9ACEM2zGaxu5.png" /></figure><h3>Operators in SQL</h3><p>Operators are used to perform operations on data. There are various types of operators in SQL, including:</p><h3>Arithmetic Operators</h3><p>These operators perform mathematical operations like addition, subtraction, multiplication, and division.</p><p>Example: SELECT salary + 5000 AS new_salary FROM employees;</p><h3>Comparison Operators</h3><p>These operators compare two values and return a boolean result.</p><p>Example: SELECT * FROM employees WHERE age &gt;= 30;</p><h3>Logical Operators</h3><p>These operators combine multiple conditions.</p><p>Example: SELECT * FROM employees WHERE age &gt;= 30 AND department = &#39;Sales&#39;;</p><h3>LIMIT Clause</h3><p>The LIMIT clause is used to specify the number of records to return.</p><p>Example: SELECT * FROM employees LIMIT 5;</p><p>This command retrieves the first 5 records from the employees table.</p><h3>ORDER BY Clause</h3><p>The ORDER BY clause is used to sort the result set in ascending or descending order.</p><p>Example: SELECT * FROM employees ORDER BY age DESC;</p><p>This command sorts the employees by age in descending order.</p><h3>Aggregate Functions</h3><p>Aggregate functions perform calculations on multiple values and return a single value. Some common aggregate functions are:</p><h3>COUNT</h3><p>Counts the number of rows.</p><p>Example: SELECT COUNT(*) FROM employees;</p><h3>SUM</h3><p>Calculates the sum of a numeric column.</p><p>Example: SELECT SUM(salary) FROM employees;</p><h3>AVG</h3><p>Calculates the average value of a numeric column.</p><p>Example: SELECT AVG(salary) FROM employees;</p><h3>MAX</h3><p>Returns the maximum value.</p><p>Example: SELECT MAX(salary) FROM employees;</p><h3>MIN</h3><p>Returns the minimum value.</p><p>Example: SELECT MIN(salary) FROM employees;</p><h3>GROUP BY Clause</h3><p>The GROUP BY clause is used to group rows that have the same values in specified columns into summary rows.</p><p>Example: SELECT department, COUNT(*) FROM employees GROUP BY department;</p><p>This command counts the number of employees in each department.</p><h3>Putting It All Together</h3><p>Here’s an example that combines operators, the LIMIT clause, the ORDER BY clause, aggregate functions, and the GROUP BY clause:</p><p>SELECT department, AVG(salary) AS average_salary FROM employees WHERE age &gt; 25 GROUP BY department ORDER BY average_salary DESC LIMIT 3;</p><p>This command retrieves the average salary of employees older than 25 in each department, sorts the results by average salary in descending order, and returns the top 3 departments.</p><p>Today’s session was incredibly informative. Each new topic builds on the last, making SQL more intuitive and powerful. I’m excited to continue my journey and learn even more.</p><p>Stay tuned for more updates on my progress!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9556096c951b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>