<?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 Shivam Baldha on Medium]]></title>
        <description><![CDATA[Stories by Shivam Baldha on Medium]]></description>
        <link>https://medium.com/@shivambaldha?source=rss-dfef99debd08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wFD83-SEKBf5-MrugtgzQQ.jpeg</url>
            <title>Stories by Shivam Baldha on Medium</title>
            <link>https://medium.com/@shivambaldha?source=rss-dfef99debd08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:45:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivambaldha/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[Binary Classification with PyTorch]]></title>
            <link>https://shivambaldha.medium.com/binary-classification-with-pytorch-85089b284940?source=rss-dfef99debd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/85089b284940</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Shivam Baldha]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 15:16:16 GMT</pubDate>
            <atom:updated>2023-10-01T15:16:16.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*n8wcMeALmTiGeWLkjsFWDQ.png" /></figure><p>In the realm of machine learning, binary classification is a fundamental task that serves as the cornerstone for numerous real-world applications. Whether it’s spam email detection, sentiment analysis, medical diagnosis, or fraud detection, binary classification plays a pivotal role in making decisions based on data. In this blog, we’ll journey to demystify binary classification using one of the most popular deep-learning libraries, PyTorch.</p><p>Binary classification involves categorizing data points into one of two classes or categories. It’s like having a magical filter separating apples from oranges, positive from negative sentiment, or healthy patients from those with a disease. The power of binary classification lies in its simplicity and applicability to a wide range of problems.</p><h3>Why PyTorch?</h3><p>PyTorch has gained immense popularity in the deep learning community due to its dynamic computation graph, flexible architecture, and robust ecosystem. It has become the go-to choice for both beginners and experts when it comes to building neural networks for various machine-learning tasks.</p><p>In this blog, we’ll explore how PyTorch simplifies the process of building, training, and evaluating binary classification models. We’ll break down the key components and steps involved, making it accessible to those new to deep learning while providing valuable insights for experienced practitioners.</p><h3>Load the Dataset</h3><p>The “sonar.all-data” dataset is a classic example in the machine learning community. It originates from sonar signal data, where the goal is to distinguish between two classes: rocks (denoted as “R”) and mines (denoted as “M”). This binary classification problem is about identifying underwater objects as either man-made mines or natural rocks based on sonar signal patterns.</p><p>Here’s what you need to know about the dataset:</p><ul><li><strong>Number of Features:</strong> Each data point in the dataset represents a sonar signal, and there are 60 numerical features. These features capture different aspects of the signals.</li><li><strong>Target Labels:</strong> The dataset has binary labels: “R” for rocks and “M” for mines.</li></ul><pre>!wget https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-dat</pre><pre>import pandas as pd<br># Read data<br>data = pd.read_csv(&quot;/content/sonar.all-data&quot;, header=None)<br>X = data.iloc[:, 0:60]<br>y = data.iloc[:, 60]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwMCPy1lpUQXUo1VCb-RqA.png" /></figure><h3>Preparing the Target Labels</h3><p>PyTorch, like many other machine learning frameworks, expects target labels to be numerical values. Label encoding is the process of mapping categorical labels to integers. In our dataset, we’ll encode “R” as 0 and “M” as 1. This encoding allows our model to compute loss, make predictions, and learn effectively.</p><pre>from sklearn.preprocessing import LabelEncoder<br>encoder = LabelEncoder()<br>encoder.fit(y)<br>y = encoder.transform(y)</pre><h3>Data to PyTorch Tensors</h3><p>Now that we’ve loaded and preprocessed our dataset, it’s time to prepare the data for consumption by our PyTorch model. PyTorch operates primarily on tensors, which are multi-dimensional arrays that can be processed efficiently on GPUs. In this section, we’ll convert our input features (X) and target labels (y) into PyTorch tensors.</p><pre>import torch<br>X = torch.tensor(X.values, dtype=torch.float32)<br>y = torch.tensor(y, dtype=torch.float32).reshape(-1, 1)</pre><h3>Building the Binary Classification Model</h3><p>In the world of deep learning, a neural network model is the heart and soul of your machine learning solution. For our binary classification task with the “sonar.all-data” dataset, we’ll create a straightforward neural network using PyTorch. This model, aptly named Deep, will serve as our binary classifier.</p><pre>class Deep(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.layer1 = nn.Linear(60, 60)<br>        self.act1 = nn.ReLU()<br>        self.layer2 = nn.Linear(60, 60)<br>        self.act2 = nn.ReLU()<br>        self.layer3 = nn.Linear(60, 60)<br>        self.act3 = nn.ReLU()<br>        self.output = nn.Linear(60, 1)<br>        self.sigmoid = nn.Sigmoid()<br><br>    def forward(self, x):<br>        x = self.act1(self.layer1(x))<br>        x = self.act2(self.layer2(x))<br>        x = self.act3(self.layer3(x))<br>        x = self.sigmoid(self.output(x))<br>        return x</pre><ul><li>Three hidden layers (layer1, layer2, and layer3), each with 60 units and ReLU activation functions.</li><li>An output layer (output) with a single unit, representing the binary classification decision.</li><li>A sigmoid activation function (sigmoid) applied to the output to squash the values between 0 and 1.</li></ul><h3>Training the Model</h3><pre>import copy<br>import numpy as np<br>import torch.nn as nn<br>import torch.optim as optim<br>import tqdm<br><br>def model_train(model, X_train, y_train, X_val, y_val):<br>    # loss function and optimizer<br>    loss_fn = nn.BCELoss()  # binary cross entropy<br>    optimizer = optim.Adam(model.parameters(), lr=0.0001)<br><br>    n_epochs = 250   # number of epochs to run<br>    batch_size = 10  # size of each batch<br>    batch_start = torch.arange(0, len(X_train), batch_size)<br><br>    # Hold the best model<br>    best_acc = - np.inf   # init to negative infinity<br>    best_weights = None<br><br>    for epoch in range(n_epochs):<br>        # print(epoch)<br>        model.train()<br>        with tqdm.tqdm(batch_start, unit=&quot;batch&quot;, mininterval=0, disable=True) as bar:<br>            bar.set_description(f&quot;Epoch {epoch}&quot;)<br>            for start in bar:<br>                # take a batch<br>                X_batch = X_train[start:start+batch_size]<br>                y_batch = y_train[start:start+batch_size]<br>                # forward pass<br>                y_pred = model(X_batch)<br>                loss = loss_fn(y_pred, y_batch)<br>                # backward pass<br>                optimizer.zero_grad()<br>                loss.backward()<br>                # update weights<br>                optimizer.step()<br>                # print progress<br>                acc = (y_pred.round() == y_batch).float().mean()<br>                bar.set_postfix(<br>                    loss=float(loss),<br>                    acc=float(acc)<br>                )<br>        # evaluate accuracy at end of each epoch<br>        model.eval()<br>        y_pred = model(X_val)<br>        acc = (y_pred.round() == y_val).float().mean()<br>        acc = float(acc)<br>        if acc &gt; best_acc:<br>            best_acc = acc<br>            best_weights = copy.deepcopy(model.state_dict())<br>    # restore model and return best accuracy<br>    model.load_state_dict(best_weights)<br>    return best_acc</pre><pre>from sklearn.model_selection import StratifiedKFold, train_test_split<br><br># train-test split: Hold out the test set for final model evaluation<br># define 5-fold cross validation test harness<br>kfold = StratifiedKFold(n_splits=5, shuffle=True)<br>cv_scores = []<br>for train, test in kfold.split(X, y):<br>    # create model, train, and get accuracy<br>    model = Deep()<br>    acc = model_train(model, X[train], y[train], X[test], y[test])<br>    print(&quot;Accuracy (wide): %.2f&quot; % acc)<br>    cv_scores.append(acc)<br><br># evaluate the model<br>acc = np.mean(cv_scores)<br>std = np.std(cv_scores)<br>print(&quot;Model accuracy: %.2f%% (+/- %.2f%%)&quot; % (acc*100, std*100))</pre><blockquote>Accuracy (wide): 0.88</blockquote><blockquote>Accuracy (wide): 0.86</blockquote><blockquote>Accuracy (wide): 0.76</blockquote><blockquote>Accuracy (wide): 0.90</blockquote><blockquote>Accuracy (wide): 0.88</blockquote><blockquote>Model accuracy: 85.61% (+/- 4.92%)</blockquote><p>Thank you for joining us on this educational journey. We hope this blog has provided you with valuable insights into the world of binary classification and PyTorch. Happy coding, and may your binary classification models be accurate and impactful!</p><p><strong>Connect with Me on LinkedIn: </strong>If you found this blog helpful and would like to stay in touch, feel free to connect with me on<strong> </strong><a href="https://www.linkedin.com/in/shivam-baldha/"><strong>LinkedIn</strong></a>. I’d love to connect with fellow enthusiasts and professionals in the field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85089b284940" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Image Size Optimization]]></title>
            <link>https://shivambaldha.medium.com/docker-image-size-optimization-be37728dc008?source=rss-dfef99debd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/be37728dc008</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devops-practice]]></category>
            <dc:creator><![CDATA[Shivam Baldha]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 12:38:14 GMT</pubDate>
            <atom:updated>2023-09-18T12:38:14.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Streamlining Docker Image Sizes: A Guide to Optimization 🐳</p><h3>Introduction</h3><p>In the world of containerization, Docker has emerged as the heavyweight champion, revolutionizing the way we package, distribute, and deploy applications. Its efficiency and portability have made it a go-to choice for developers and DevOps teams worldwide. However, there’s one aspect of Docker that often perplexes even seasoned professionals: image size.</p><p>Docker images are the foundation of containerization, containing everything a container needs to run a specific application. While Docker’s benefits are undeniable, the size of these images can sometimes bloat, leading to slower deployment times, increased storage requirements, and even potential security vulnerabilities. This is where Docker image size optimization comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-YgL1NW7evYyCBWI-7w8Q.png" /></figure><p>In this blog, we’re going to delve deep into the world of Docker image optimization, exploring strategies, best practices, and tools that can help you trim the excess and create leaner, more efficient Docker images. Whether you’re a beginner looking to understand the basics or a seasoned pro seeking advanced techniques, our journey through Docker image size optimization will equip you with the knowledge and skills to streamline your containers and supercharge your DevOps workflow.</p><p>So, fasten your seatbelts, as we embark on a voyage to transform your Docker images from heavyweights into featherweights. It’s time to harness the power of Docker and make your containerized applications not only efficient but also nimble. Let’s dive into the exciting world of Docker image size optimization! 🐳🔍</p><h3>How to optimize Docker image size?</h3><h4>1. Choose a Lean Base Image</h4><p>When it comes to Docker image optimization, your journey should begin with a slim and minimalistic base image. Opt for lightweight choices like Alpine Linux or even Scratch. By doing so, you’ll minimize unnecessary layers in your Docker image right from the start. Remember, starting with a clean slate sets the foundation for a more efficient and compact container.</p><h4>2. Embrace Multi-Stage Builds</h4><p>In the quest to optimize Docker image sizes, multi-stage builds are your best friend. 🏗️ These builds allow you to streamline the container creation process. Start by compiling your code, dependencies, and libraries in an intermediate image, and then cherry-pick only the essential artifacts to include in your final image. This approach significantly reduces the size of your Docker image, making it more nimble and resource-efficient.</p><p>By implementing these two fundamental strategies, you’ll be well on your way to mastering Docker image size optimization. So, let’s dive deeper into these techniques and explore additional tricks to ensure your Docker containers are as efficient as possible! 🚀🐳</p><h4>3. Streamline Your Dockerfile Layers 🍕</h4><p>In the realm of Docker image optimization, simplicity is key. Each instruction in your Dockerfile generates a new layer, and these layers can quickly add up. To keep your Docker image size in check, aim to minimize the number of layers.</p><p>One effective technique is to consolidate commands whenever possible. For instance, instead of creating separate layers for various actions, harness the power of RUN commands by using the &amp;&amp; operator to chain multiple actions together within a single step. This approach not only reduces the number of layers but also makes your Dockerfile more concise and easier to maintain.</p><h4>4. Tidy Up After Each Step 🧽</h4><p>In the pursuit of Docker image optimization, it’s crucial to maintain a tidy workspace within your containers. To achieve this, make it a habit to clean up after each step in your Dockerfile. By removing temporary files, cached package lists, and other unnecessary artifacts within the same RUN command, you can prevent them from becoming permanent residents in your final image.</p><p>This meticulous approach not only helps you keep your Docker images lean but also ensures that you’re not carrying excess baggage along the way. The result? Containers that are both more efficient and more secure.</p><h4>5. Package Manager Precision 📦</h4><p>When it comes to Docker image optimization, your choice of package manager flags can make a world of difference. To maintain a trim and efficient container, exercise precision when using package managers. Leverage flags such as --no-cache or --purge to prevent the accumulation of redundant files in your image.</p><p>These flags allow you to control the caching and cleanup of package manager operations, ensuring that only essential components are retained. By doing so, you’ll significantly reduce the footprint of your Docker image, leading to faster deployments and more efficient resource utilization.</p><h4>6. Choose Compact Alternatives 🐚</h4><p>In the realm of Docker image optimization, sometimes less is more. When selecting tools or libraries for your container, consider smaller alternatives that can fulfill your requirements. If a lightweight counterpart serves your purpose effectively, it’s a smart choice.</p><p>For instance, opt for BusyBox utilities instead of their larger GNU counterparts when feasible. This switch to compact alternatives can significantly reduce the size of your Docker image while still maintaining the functionality you need. It’s a strategic move to keep your containers agile and resource-efficient.</p><h4>7. Image Layer Optimization 🍰</h4><p>When it comes to Docker image size optimization, the order of instructions in your Dockerfile matters. To create a more efficient image, strategically organize your Dockerfile so that components that change frequently, such as application code, come later in the file. This clever arrangement allows Docker to reuse cached layers for the stable parts of your image.</p><p>By adopting this layering strategy, you minimize unnecessary rebuilding of unaltered layers, leading to faster build times and more efficient use of resources. It’s a key practice in the art of Docker image optimization that can make a substantial difference in your containerization process.</p><h4>8. Artifact Compression 🗜️</h4><p>In the quest for Docker image optimization, don’t overlook the power of compression. If your Docker image includes application assets or files, consider compressing them before copying them into the image. This seemingly small step can yield significant reductions in image size.</p><p>Compression not only shrinks the size of your artifacts but also enhances the efficiency of your container. Smaller images lead to faster deployments and lower storage requirements, a win-win scenario for any Docker-based project.</p><h3>In Conclusion: Your Path to Dockerfile Optimization</h3><p>As we wrap up this exploration of Docker image size optimization, it’s essential to distill the key takeaways. These best practices, inspired by insights shared by <a href="https://twitter.com/devops_tech"><strong>Rakesh Jain</strong></a>, are invaluable for anyone venturing into the world of containerization. By keeping these principles in mind, you’ll empower yourself to craft Dockerfiles that are lean, efficient, and highly performant.</p><p>From choosing a minimalist base image and embracing multi-stage builds to meticulous cleanup and precise package management, every step contributes to the ultimate goal: a streamlined Docker image. Moreover, considering compact alternatives and optimizing layer organization are vital aspects of this journey. Finally, don’t forget the power of compression to further reduce image size.</p><p>We owe our gratitude to Rakesh Jain for sharing these valuable insights with the developer community. Such knowledge sharing strengthens the foundations of our tech world, enabling us all to create more efficient and sustainable software solutions.</p><p>So, as you embark on your Dockerfile optimization endeavors, remember these guiding principles. They will not only make your containers lighter and faster but also elevate your skills as a containerization maestro.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be37728dc008" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All You Need To Know About the Seldon-Core]]></title>
            <link>https://shivambaldha.medium.com/all-you-need-to-know-about-the-seldon-core-e28aa6b97dc0?source=rss-dfef99debd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28aa6b97dc0</guid>
            <category><![CDATA[seldon]]></category>
            <category><![CDATA[seldon-core]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Shivam Baldha]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 04:36:47 GMT</pubDate>
            <atom:updated>2022-09-18T08:35:55.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setup the Seldon and Deploy the ML Model with Seldon</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1hPNWfa19KCa0dpx.png" /></figure><h3>What is Seldon?</h3><p>It is an open-source platform to deploy your machine learning models on Kubernetes at a massive scale. that enables data science teams to easily run and manage models in production at scale.</p><p>Seldon Core focuses on solving the last step in any machine learning project to help companies put models into production, to solve real-world problems, and maximize the return on investment. More about.</p><p>Seldon core converts your ML models (TensorFlow, Py torch, H2o, etc.) or language wrappers (Python, Java, etc.) into production REST/GRPC microservices (break down the whole app into small chunks and they are connected to each other).</p><p>Seldon handles scaling to thousands of production machine learning models and provides advanced machine learning capabilities out of the box including Advanced Metrics, Request Logging, Explainers, Outlier Detectors, A/B Tests, Canaries, and more.</p><h3>What are microservices?</h3><p>When we need to wright the application we would start a new code project, and we would add functionality to our application, we add more code, so the size of the code increases over time.</p><p>So, developers were recommended to break things up into modules rather than put all code into a single mess of the codebases, create the smaller module and compose your application from these modules. So, this small module is the microservice, more about this click here.</p><p>Seldon Core runs on any cloud platform, on bare metal servers and individual laptops. Here we set up the seldon core on the Azure cloud.</p><h3>Prerequisites to setup the seldon</h3><p><strong>Azure Cloud CLI</strong></p><p>To install Azure CLI, follow this link (<a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli">Setup the CLI</a>).</p><p><strong>Create the AKS (Azure Kubernetes Service Cluster)</strong></p><p>Go to the Create the resource, and create the Kubernetes service,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-vmidYPwSrdbg1q45Tc5Q.png" /></figure><p>Once Cluster is created and connect them with the cluster and follow the command which is given by Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVgtoH-Rf9AgyxZgzV61nQ.png" /></figure><p><strong>Kubectl command line</strong></p><p>The Kubernetes command-line tool, <a href="https://kubernetes.io/docs/reference/kubectl/kubectl/">kubectl</a>, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs.</p><p>Now after this install the kubectl command line, now by azure provides the Linux os, so we follow the Linux command line tools. To install kubectl follow this docx (<a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/">click here</a>)</p><p><strong>Install the Helm</strong></p><p>Helm is the package manager for Kubernetes, and Helm helps you manage Kubernetes applications.</p><p>Install helm (<a href="https://helm.sh/docs/intro/install/">click here</a>)</p><p><strong>Install Cluster Ingress</strong></p><p>Ingress is a Kubernetes object that provides routing rules for your cluster. It manages the incoming traffic and routes it to the services running inside the cluster.</p><p>Seldon Core supports using either <a href="https://istio.io/">Istio</a> or <a href="https://www.getambassador.io/">Ambassador</a> to manage incoming traffic. Seldon Core automatically creates the objects and rules required to route traffic to your deployed machine learning models.</p><p>To manage the incoming traffic, we use the Istio package. To install the Istio follow this one and <a href="https://docs.seldon.io/projects/seldon-core/en/latest/install/azure.html#install-cluster-ingress">click here</a> or you can run the below command one by one.</p><pre>curl -L https://istio.io/downloadIstio | sh -</pre><pre>cd istio-1.11.4</pre><pre>export PATH=$PWD/bin:$PATH</pre><pre>istioctl install --set profile=demo -y</pre><pre>kubectl label namespace default istio-injection=enabled</pre><blockquote>You will need to copy the entire command from the code block below</blockquote><pre>kubectl apply -f - &lt;&lt; END<br>apiVersion: networking.istio.io/v1alpha3<br><strong>kind</strong>: Gateway<br><strong>metadata</strong>:<br>  <strong>name</strong>: seldon-gateway<br>  <strong>namespace</strong>: istio-system<br><strong>spec</strong>:<br>  <strong>selector</strong>:<br>    <strong>istio</strong>: ingressgateway <em># use istio default controller</em><br>  <strong>servers</strong>:<br>  - <strong>port</strong>:<br>      <strong>number</strong>: 80<br>      <strong>name</strong>: http<br>      <strong>protocol</strong>: HTTP<br>    <strong>hosts</strong>:<br>    - &quot;*&quot;<br>END</pre><p>Now we can set to set-up the seldon core in our cloud, to set up the seldon core follow this command, or run the below command into your CLI.</p><h3>Install Seldon Core</h3><p>Before we install Seldon Core, we’ll create a new namespace seldon-system for the operator to run in:</p><pre>kubectl create namespace seldon-system</pre><p>We’re now ready to install Seldon Core in our cluster. Run the following command for your choice of Ingress:</p><pre>helm install seldon-core seldon-core-operator <strong>\</strong><br>    --repo https://storage.googleapis.com/seldon-charts <strong>\</strong><br>    --set usageMetrics.enabled=true <strong>\</strong><br>    --set istio.enabled=true <strong>\</strong><br>    --namespace seldon-system</pre><p>You can check that your Seldon Controller is running by doing:</p><pre>kubectl get pods -n seldon-system</pre><p>You should see a seldon-controller-manager pod with STATUS=Running.</p><h4>Accessing your models</h4><p>Congratulations! Seldon Core is now fully installed and operational. Before you move on to deploying models, make a note of your cluster IP and port:</p><pre>export INGRESS_HOST=<strong>$(</strong>kubectl -n istio-system get service istio-ingressgateway -o jsonpath=&#39;{.status.loadBalancer.ingress[0].ip}&#39;<strong>)</strong></pre><pre>export INGRESS_PORT=<strong>$(</strong>kubectl -n istio-system get service istio-ingressgateway -o jsonpath=&#39;{.spec.ports[?(@.name==&quot;http2&quot;)].port}&#39;<strong>)</strong></pre><pre>export INGRESS_URL=$INGRESS_HOST:$INGRESS_PORT</pre><pre>echo $INGRESS_URL</pre><h3>Deploy ML Model with Seldon-core</h3><p>To Deploy any machine learning model with the seldon core first we build one simple ML model with the .py file, and the seldon core expects the .py file as some particular format, basically, our model is defined inside the class in .py files, for eg I will mention the GitHub link to the end of the blog.</p><p>After this, we create one requirements.txt file and one Docker file, then now we build the one docker image.</p><p>Also, we have to create one folder, and the name is .s2i, and inside the folder, we have one environment file and here we have to give our Class name which we created in the .py file</p><p>where yourusername is your docker hub username, To learn more about docker commands <a href="https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/">click here</a>.</p><pre>docker build -t yourusername/image-name</pre><p>Once the docker image is built successfully then we containerize our class file using the <a href="https://docs.seldon.io/projects/seldon-core/en/latest/wrappers/s2i.html">Seldon Core s2i utils</a> to produce the image.</p><p><strong>Install S2i (source-to-image)</strong></p><p>So install S2i follow this link <a href="https://github.com/openshift/source-to-image/releases/tag/v1.3.1">https://github.com/openshift/source-to-image/releases/tag/v1.3.1</a>, find the window assets, and download the zip file,</p><p>then unzip the file and put this unzip file folder into the Program files folder and add the path of this folder inside the environment variables.</p><p>Once s2i is installed then we follow the below command and produce the image.</p><pre>s2i build . seldonio/seldon-core-s2i-python3:0.18 &lt;yourusername /image-name&gt;</pre><p>After this, we push this image into the container like a Docker hub container.</p><p>Now we push the image into the docker hub using this command and first, we log in to the docker.</p><pre>docker login</pre><pre>docker push &lt;yourusername /image-name&gt;</pre><p>And we now deploy it to our Seldon Core Kubernetes Cluster:</p><pre>kubectl apply -f - &lt;&lt; END<br>apiVersion: machinelearning.seldon.io/v1<br><strong>kind</strong>: SeldonDeployment<br><strong>metadata</strong>:<br>  <strong>name</strong>: &lt;your-model-name&gt;<br>  <strong>namespace</strong>: &lt;your-model-namespace&gt;<br><strong>spec</strong>:<br>  <strong>name</strong>: iris<br>  <strong>predictors</strong>:<br>  - <strong>componentSpecs</strong>:<br>    - <strong>spec</strong>:<br>        <strong>containers</strong>:<br>        - <strong>name</strong>: classifier<br>          <strong>image</strong>: &lt;yourusername /image-name&gt;<br>    <strong>graph</strong>:<br>      <strong>name</strong>: classifier<br>    <strong>name</strong>: default<br>    <strong>replicas</strong>: 1<br>END</pre><p>To more about the docker <a href="https://www.cloudbees.com/blog/using-docker-push-to-publish-images-to-dockerhub">click here</a>.</p><p>This can be accessed through the endpoint http://&lt;ingress_url&gt;/seldon/&lt;namespace&gt;/&lt;model-name&gt;/api/v1.0/doc/ which will allow you to send requests directly through your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LChDKZvXto9RdMM5.jpg" /></figure><p>Here inside the ndarray is your input.</p><p>To do an experiment and find the code below.</p><p><a href="https://github.com/shivambaldha/Seldon-Core/tree/main">GitHub - shivambaldha/Seldon-Core: Setup the Seldon and Deploy the ML Model with Seldon</a></p><p><strong>More reference to learn more about seldon-core.</strong></p><ul><li><a href="https://betterprogramming.pub/serving-deploying-ml-models-with-seldon-core-on-kubernetes-2022-eb459bb4d47a">Serving and Deploying ML Models With Seldon Core on Kubernetes 2022</a></li><li><a href="https://doc.lucidworks.com/how-to/820/develop-and-deploy-a-machine-learning-model">Develop and Deploy a Machine Learning Model</a></li></ul><p>That’s all….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28aa6b97dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gmail Smart Compose]]></title>
            <link>https://shivambaldha.medium.com/gmail-smart-compose-ad4c0f311d5b?source=rss-dfef99debd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4c0f311d5b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[language-model]]></category>
            <dc:creator><![CDATA[Shivam Baldha]]></dc:creator>
            <pubDate>Wed, 25 May 2022 18:15:35 GMT</pubDate>
            <atom:updated>2022-05-27T07:37:34.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>Language Modeling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJlRxXhIxniOzmI266rM1A.jpeg" /><figcaption><a href="https://techcrunch.com/">Source</a></figcaption></figure><h3>Table Contents</h3><ol><li>Introduction</li><li>Business problem</li><li>Source of data</li><li>Business Constraints</li><li>Performance Metrics</li><li>Problem Formulation</li><li>Existing Approaches</li><li>Improvements</li><li>Exploratory Data Analysis and its Observation</li><li>Data Cleaning</li><li>Data Preparation</li><li>Modeling</li><li>Model Comparison</li><li>A Final Pipeline Of The Problem</li><li>Conclusion</li><li>Future Work</li><li>References</li><li>GitHub Repo</li></ol><h3>Prerequisite</h3><p>You have to have knowledge about deep learning algorithms, and encoder-decoder modeling.</p><h3>1. Introduction</h3><p>AS we all know about the E-mail, the E-mail continues to be a ubiquitous and growing form of communication all over the world, with an estimated 3.8 billion users sending 281 billion e-mails daily.</p><p>All you have experienced the Gmail smart compose, maybe even without knowing you all are actually using Gmail smart compose in daily life. Maybe you notice when typing an email, sometimes Gmail suggests the relevant or relevant sentences, this is nothing but Gmail smart compose.</p><h3>2. Business problem</h3><p>So here is the task we have to make a model, which can predict the sentences or words based on the given sentence or some words. the input is a sequence of words and the output is also a sequence of words, so we have to build the sequence-based model.</p><p>To generate the next word or next word prediction is also called a language modeling task.</p><h3>3. Source of data</h3><p>The dataset we use is The Enron Email Dataset, and the dataset contains 500,000+ emails from 150 employees of the Enron Corporation. It was obtained by the Federal Energy Regulatory Commission during its investigation of Enron’s collapse.</p><p>For this task, our data is Gmail conversation-based data. I took this data from the <a href="https://www.kaggle.com/datasets/wcukierski/enron-email-dataset">Kaggle</a>, and the data set contain only two columns, the first column is the file’s name, and the second one is the message.</p><p>Overview of the message:</p><pre>Message-ID: &lt;22766758.1075855690869.JavaMail.evans@thyme&gt;<br>Date: Fri, 26 May 2000 00:08:00 -0700 (PDT)<br>From: phillip.allen@enron.com<br>To: stagecoachmama@hotmail.com<br>Subject: Re: Todays update<br>Mime-Version: 1.0<br>Content-Type: text/plain; charset=us-ascii<br>Content-Transfer-Encoding: 7bit<br>X-From: Phillip K Allen<br>X-To: &quot;Lucy Gonzalez&quot; &lt;stagecoachmama@hotmail.com&gt; @ ENRON<br>X-cc: <br>X-bcc: <br>X-Folder: \Phillip_Allen_Dec2000\Notes Folders\&#39;sent mail<br>X-Origin: Allen-P<br>X-FileName: pallen.nsf<br><br>Lucy,<br> I am going to be in Seguin this Saturday through Monday.  We can talk about <br>a unit for Wade then.  I will call the bank again today to resolve <br>authorization on the account.  Lets keep the office open until noon on <br>Memorial day.<br><br>Philllip</pre><p>From this mail we have to extract the message, we will learn in this blog how to extract the message.</p><h3>4. Business constraints</h3><ol><li>The predicted value should be the word or sentence.</li><li>Strict latency constraints.</li></ol><h3>5. Performance metrics</h3><p>As the performance metrics, we use the BLEU (Bilingual Evaluation Understudy) score, which is a score for comparing a candidate&#39;s translation of the text to one or more reference translations, and more about a <a href="https://machinelearningmastery.com/calculate-bleu-score-for-text-python/">blue score</a>.</p><p>Why did we choose the BLUE score?</p><ol><li>It is quick and inexpensive to calculate.</li><li>It is easy to understand.</li><li>It is language-independent.</li><li>It correlates highly with human evaluation.</li><li>It has been widely adopted.</li></ol><h3>6. Problem formulation</h3><p>sequence and language modeling base task we have, the next word prediction is also called language modeling.</p><p>So here our input and output are the sequences of words and we have to predict the sequence of words given the input of sentences.</p><p>Here the use of a Neural network-based model is preferable to the simple modeling task, the task is a sequence-based task, so we can use sequence-to sequence-based models like LSTM, and GRU, and also we can use Encode decoder based model.</p><p>To create the data we can use the word n-gram like this, let&#39;s suppose we have the one sentence ‘here is our mail’ so our X and Y look like this,</p><pre>X             Y<br>here          is our mail<br>here is       our mail<br>here is our   mail</pre><p>Now we convert each message into this word char and we use it as our dataset.</p><h3>7. Existing approaches</h3><p><strong>Solution 1</strong></p><p><a href="https://arxiv.org/pdf/1906.00080.pdf">https://arxiv.org/pdf/1906.00080.pdf</a></p><p><strong>Observation:</strong></p><p>This is the main research paper on the implementation of Smart Gmail Compose.</p><p>In this paper first, they talked about some Challenges which they faced Like Latency, here we have to predict the next words In very less time, the second one is scale, we know the Gmail has a very high number of users so implement this services for all user is the one challenge.</p><p>Here in section 2, they talked about the related work, especially the application of language models in different tasks, Smart Compose is an example of a largescale language model application.</p><p>In section 3 they talked about the model, we know The fundamental task in Smart Compose is to predict a sequence of tokens of variable length, conditioned on the prefix token sequence typed by a user and additional contextual information.</p><p>Finding the model that maximizes the log probability of producing the correct target sequence given the input for all data samples in the training corpus.</p><p>Here they talked about the two different models, 1 = Language model A and 2 = language model B.</p><p><strong>Solution 2</strong></p><p><a href="https://towardsdatascience.com/gmail-style-smart-compose-using-char-ngram-language-models-a73c09550447">https://towardsdatascience.com/gmail-style-smart-compose-using-char-ngram-language-models-a73c09550447</a></p><p><strong>Observation:</strong></p><p>In this article they talked about Neural Machine Translation, NMT (Neural Machine Translation) has to sort of becoming the canonical use case for explaining sequence to sequence models (Seq2Seq models).</p><p>After this, they talked about the basic seq2seq model like LSTM and GRU, and the language model(LM).</p><p>LMs learn a representation of a text corpus similar to a word embedding but a better one. LM is to break up a text corpus and assign probabilities to text sequences, typically one word at a time. (but there are other variants).</p><p><strong>Solution 3</strong></p><p><a href="https://blog.jiayihu.net/gmail-smart-compose-in-keras-and-tensorflow-js/">https://blog.jiayihu.net/gmail-smart-compose-in-keras-and-tensorflow-js/</a></p><p><strong>Observation</strong></p><p>Here they talked about some important things about the datasets, we know Google use the previous email to predict the new words token, but Unfortunately, the Enron dataset is a flattened set of emails with no information about conversations other than the subject.</p><p>They also use the log perplexity (the metric used to evaluate the models) as the log perplexity goes low model becomes better. Also, they talked about some good tips for data cleaning.</p><p>To train the model they use the Encoder decoder model with the GRU units and During the training, the model uses teacher forcing.</p><p><strong>Solution 4</strong></p><p><a href="https://medium.datadriveninvestor.com/smart-compose-in-email-usingdeep-learning-c9cc29d9d60a">https://medium.datadriveninvestor.com/smart-compose-in-email-usingdeep-learning-c9cc29d9d60a</a></p><p><strong>Observation:</strong></p><p>Here in this blog author talked about his first cut approach and they use the simple deep learning model RNN with the LSTM units and the last layer uses a Soft-max classifier.</p><p>We can also implement a first cut approach in our case study with some changing in the units,</p><p>So this blog tells us about the general idea of using a basic language modeling technique to make smart predictions.</p><h3>8. Improvements</h3><p>Here is the biggest challenge for me cleaning the data, here we saw in the mail message file contains many unwanted things like mail id, subject name, phone number, etc. mail message maybe contain the personal details like bank account number, personal files, phone number, so while cleaning the data we have to make sure we remove the all these details.</p><p>As part of the improvement, I create the data set with the three columns such that the first one is input as the encoder part, the second one is input as the decoder part and the third one is our target values.</p><p>So here I used the encoder decore as the molding part in this case study.</p><h3>9. Exploratory data analysis (EDA) and its observation</h3><p>EDA will help us to understand data more clearly. with the help of EDA, we can do more data cleaning and this is useful to increase the BLUE score.</p><h4>9.1 Load the data and visualize</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4S1EKlWjsilPzTDNfoiCyw.png" /><figcaption>Our Dataset</figcaption></figure><p>Here we have only two columns in the datasets.</p><h4>9.2 Distribution of mail message</h4><p>Before plotting the distribution we have the extract the message from the mail, to extract the message there is a very good library which is the email library.</p><p>This library converts each mail message into a tuple of a list and we take the message tuple from the list as our message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPK-ZtSXxmYbcQ_PRllpwg.png" /><figcaption>Use of email library</figcaption></figure><p>Now we take the length of the message and plot the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*1n5sAxMIYbfZTDxr7fCvZg.png" /><figcaption>Histogram of a mail message</figcaption></figure><p>Here we take the random 1500 mail and we plot the histogram of the length of mail.</p><p>From the histogram, we can say there are many mail messages where the length of the message is between 1000 to 10000 and a very small part of the message where the length message is above the 30000.</p><p>I think is very long message is not adding much more value to our study so we remove all these types of messages from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*XoDGdlNNtO0C5HGw1hOSEQ.png" /></figure><p>Here we take the sample of data, and we plot the distribution of the mail message length, the distribution falls down very sharply and the tail of the distribution is very long.</p><p>so we can say here the more message length is between the 0 to 10k and very less point has a length of more than the 10k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*Wn4MHS0ST7CddFndwnluww.png" /><figcaption>Cdf of a mail message</figcaption></figure><p>From the CDF we can say that 99% of the data mail message length is less than the 10k.</p><h4>9.3 Remove the long mail message</h4><p>Here we find the percentile values of the mail message length and we use the percentile values we remove the unwanted mail message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sieXxE2W2pfN0ned-66_tQ.png" /></figure><p>In the first section, we find the 5 to 100 percentile values and the 5 percentile value is 58 which means the 5 percent data has a length is 58, but the 95 to 100 percentile values increase the very fast, so let’s zoom the values of 95 to 100 percentile values.</p><p>In the second, we take the 90 to 100 percentile values and we show that the 99 percent data length is 16k but in 99 to 100 percent value increases very fast, so we zoom further.</p><p>In the third section we take the 99 to 100 percentile values and the message length increase very fast so here we take only 5 to 95 percentile values and the rest of the data we remove from the dataset.</p><h4>9.3 After the removing the long mail message</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IeSlKFuMeysOZM3LDMVdLQ.png" /><figcaption>After removing the unwanted message</figcaption></figure><p>After the removal of the unwanted mail message length, our histogram looks very clear and most of the mail message length is less than the 3000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*kQO_UmnBhpTDvRuFoSDULQ.png" /><figcaption>Q-Q plot of the data</figcaption></figure><p>From the Q-Q plot, we can say the length of the message is not follow the normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*qmoDunaOiNR3LKgu9pz5UA.png" /><figcaption>Word cloud of the mail message</figcaption></figure><p>Here the more frequent words are ‘let me know’, ‘deal’, ‘please’, etc.</p><h3>10. Data cleaning</h3><p>Here cleaning data mail messages I used the <strong>regular expression function.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36f34d368114df9c0c7ac4386b3c9b58/href">https://medium.com/media/36f34d368114df9c0c7ac4386b3c9b58/href</a></iframe><p>Here is the code part to remove all the unwanted parts from the mail message.</p><h4>10.1 Remove sentences that contain rare words</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*jw8BShGNA4czY-OBTrdqXw.png" /><figcaption>Bar plot</figcaption></figure><p>In this bar graph, we plot the counts of words that occur in the whole corpus, vs words in a sentence, here we converted each word into a token, so we have a total of 350k words in our corpus.</p><p>Very few words occur more than 5 times, and we have removed all rare words in the corpus.</p><p>we remove all the words which not occur more than 150 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsd5iX6zjW3cQksvkFdECA.png" /><figcaption>After cleaning the mail message</figcaption></figure><h3>11. Data preparation</h3><p>In this study, word-based models are developed. For training the model, the data is featurization in a specific way which is discussed below part.</p><h4>11.1 word featurization</h4><p>As we know our task is given sentences or words we have to predict the words or sentences, in our dataset, we have sentences, for the word featurization we split each sentence into words and we generate the new dataset.</p><p>Here we use an encoder-decoder-based model so we have two inputs, the first one for the encoder part and the second one for the decoder part, and one we have the target variables.</p><p>To understand more we take one eg.</p><p>Our input is “plus your thoughts on” and our output is “any changes that need to be made”, so our prediction must be an “any changes that need to be made”.</p><p>As we know in the encoder part our input starts with the ‘&lt;start&gt;’ token and ends with the ‘&lt;end&gt;’ token.</p><p>In the decoder part input starts with the ‘&lt;start&gt;’ token and output ends with the ‘&lt;end&gt;’ keyword.</p><p>So we have to convert our data into this format. by adding this token model know where the sentence starts and where the sentence ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxQ20yCSiF-LsPCfYoSzww.png" /><figcaption>word featurization</figcaption></figure><h3>12. Modeling</h3><p>In our study, we first build the baseline model and after this, we try different models.</p><h4>12.1 Baseline Model</h4><p>As a baseline model, I build a very simple model with the LSTM units, and of course, the baseline model dataset is a little bit different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OreYxCAOC8T78wcRWvpgWQ.png" /><figcaption>Dataset for the baseline model</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe979e975b28486da141443fea23d78/href">https://medium.com/media/8fe979e975b28486da141443fea23d78/href</a></iframe><p>It consists of an embedding layer, LSTM layer, and dense layer and at the last layer, we want the probability of the words because we take those words whose probability is high so we use a softmax as the activation unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*di2g_rTBugHxnDO3aJTbNw.jpeg" /></figure><p>After training the model we got a BLUE score is 0.20631. By using the other model, we have to improve the BLUE score.</p><h4>12.2 Encoder-Decoder Model</h4><p>Here I used an encoder-decoder-based model.</p><p><a href="https://github.com/shivambaldha/Gmail_Smart_Compose/blob/main/5_New_Modeling.ipynb">Gmail_Smart_Compose/5_New_Modeling.ipynb at main · shivambaldha/Gmail_Smart_Compose</a></p><p>The encoder consists of an embedding layer, an LSTM layer, and a batch normalization layer.</p><p>First, we feed our data into the encoder part, which contains the two layers, first, our data goes to the Embedding layer where we convert each word into the same size matrix, and then we pass this matrix into the LSTM layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7a0ShsYNCjxs-lNeux8MA.png" /><figcaption>Encoder-decoder Model</figcaption></figure><p>So last output of the LSTM layer is an input of the Decoder model, as shown in the above fig we feed the last output of the lstm layer into the decoder model and this generates the words.</p><p>Each time we give a bunch of words and the model predicts the bunch of words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*JbYjY5e6gfWUgZUO6B0mHA.png" /></figure><p>After the 45 epoch, we can see that the loss is constant in the validation data, and in the training, data loss is decreasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVsGMiYaUZTDoadOAUY8vA.png" /><figcaption>Prediction of the encoder-decoder model</figcaption></figure><p>Here the prediction of the model is good, all prediction is meaningful. After training the model we got a BLUE score is 0.71593, which this very high than the baseline model.</p><h4>12.3 Encoder-Decoder Model With Attention</h4><p>The model consists of an encoder, attention mechanism, one-step decoder, and the decoder (repeats the one-step decoder).</p><p>encoder decoder with attention model structure.</p><p><a href="https://github.com/shivambaldha/Gmail_Smart_Compose/blob/main/5_New_Modeling.ipynb">Gmail_Smart_Compose/5_New_Modeling.ipynb at main · shivambaldha/Gmail_Smart_Compose</a></p><p>This encoder structure is the same as the encoder-decoder model. after the encoder part we have the attention mechanism, and the input to the attention mechanism is the encoder output of all timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoJftCb4xJQBn6l6bqu0Hw.jpeg" /></figure><p>After the attention layer, we have one step decoder, this one-step decoder contains an attention mechanism, embedding layer, LSTM layer, and dense layer.</p><p>The attention mechanism computes the context vector from the encoder output.</p><p>And then we have the decoder layers, and the decoder runs the one-step decoder for each timestep of decoder input.</p><p>And then we have the last layer which is the encoder-decoder layer, which takes the input data.</p><p>To learn how all layers work in more detail: <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9072638">https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9072638</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*OnE63DjlDQt61_db-8yw1A.png" /></figure><p>After the 27 epochs, we can see that the loss is constant in the validation data, and in the training, data loss is decreasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4qbUWF4yiQCeuoQM2GaJQ.png" /><figcaption>Prediction by Encoder-Decoder Model With Attention</figcaption></figure><p>Here the prediction of the model is good, all prediction is meaningful. After training the model we got a BLUE score is 0.50118, which this very high than the baseline model but not good as the simple encoder-decoder model. so we use the simple encoder-decoder model as our final model.</p><h3>13. Model comparison</h3><p>After running all the three models on our data we can say that the encoder-decoder model is very good than the other model,</p><p>Encoder-decoder and Encoder-decoder with attention both predict the very meaningful sentences but the good one is encoder-decoder, so we use this model as the final model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*vVz7Gp2Zux72OdPH0X42-Q.png" /></figure><h3>14. A final pipeline of the problem</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc8a1280153a8ca5e108628aeb3dc1d/href">https://medium.com/media/1dc8a1280153a8ca5e108628aeb3dc1d/href</a></iframe><ul><li><strong>Inputs:</strong> as input, we give a sentence.</li><li>Eg. ‘if you have’</li><li><strong>Output: </strong>relevant or irrelevant words.</li><li>Eg. ‘any questions please call me’</li></ul><p><strong>Model deployed on local box (Video)</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvgs3ufXGDm4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dvgs3ufXGDm4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvgs3ufXGDm4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e4275cde5a2cf00b62b90b5b12866f/href">https://medium.com/media/e0e4275cde5a2cf00b62b90b5b12866f/href</a></iframe><p>Model deployed on the streamlit link,</p><p><a href="https://share.streamlit.io/shivambaldha/gmail_smart_compose_app/main/app.py">https://share.streamlit.io/shivambaldha/gmail_smart_compose_app/main/app.py</a></p><h3>15. Conclusion:</h3><ol><li>Encoder decoder models without attention perform much better than the with attention mechanism model.</li><li>The predictions of the non-attention-based model are more relevant than the attention-based model.</li><li>A simple LSTM based model is not useful and the BLUE score is also very low than the other models</li></ol><h3>16. Future work:</h3><p>The possible improvements that can be made to improve our solution are as follows:</p><ol><li>Generate the Character featurization and then apply the encoder-decoder models</li><li>Using more powerful models like GTP, and GTP2.</li><li>Using pre-trained BERT embeddings and GloVe embeddings for word-based models.</li><li>Modifying the architecture of encoder-decoder models by incorporating multi-layer LSTM or bidirectional LSTM and skip connections.</li></ol><h3>17. References</h3><ol><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li><li><a href="https://arxiv.org/pdf/1906.00080.pdf">https://arxiv.org/pdf/1906.00080.pdf</a> main research paper</li><li><a href="https://ai.googleblog.com/2018/05/smart-composeusing-neural-networks-to.html">https://ai.googleblog.com/2018/05/smart-composeusing-neural-networks-to.html</a></li><li><a href="https://blog.jiayihu.net/gmail-smart-compose-in-keras-and-tensorflow-js/">https://blog.jiayihu.net/gmail-smart-compose-in-keras-and-tensorflow-js/</a></li><li><a href="https://medium.com/@jubergandharv/email-smart-compose-real-timeassisted-writing-b232191d0681">https://medium.com/@jubergandharv/email-smart-compose-real-timeassisted-writing-b232191d0681</a></li><li><a href="https://www.analyticsvidhya.com/blog/2018/05/google-using-neural-networks-help-write-emails-smart-compose/">https://www.analyticsvidhya.com/blog/2018/05/google-using-neural-networks-help-write-emails-smart-compose/</a></li><li><a href="https://www.kaggle.com/questions-and-answers/79467">https://www.kaggle.com/questions-and-answers/79467</a></li></ol><h3>18. GitHub Repo</h3><p><a href="https://github.com/shivambaldha/Gmail_Smart_Compose">GitHub - shivambaldha/Gmail_Smart_Compose: Problem statement : So here is the task we have to make a model, which can predict the sentences or words based on the given sentence or some words.</a></p><p><a href="https://www.linkedin.com/in/shivam-baldha/"><strong>Linkedin Profile</strong></a></p><p>That’s all…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4c0f311d5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LANL Earthquake Prediction]]></title>
            <link>https://shivambaldha.medium.com/lanl-earthquake-prediction-27befe882a40?source=rss-dfef99debd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/27befe882a40</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[Shivam Baldha]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 17:31:28 GMT</pubDate>
            <atom:updated>2022-04-27T18:40:02.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time-series and Regression.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*NvUxfqFvfVkOPLXzLcwYvA.jpeg" /><figcaption><a href="https://www.aessoil.com/wp-content/uploads/2016/01/iStock-527890380.jpg">Source</a></figcaption></figure><h3>Table Contents</h3><ol><li>Introduction</li><li>Business problem</li><li>Source of data</li><li>Business Constraints</li><li>Performance Metrics</li><li>Using of Machine Learning</li><li>Existing Approaches</li><li>Improvements</li><li>Exploratory Data Analysis and its Observation</li><li>My First Cut Approach to the above problem</li><li>Feature engineering</li><li>Modeling and Comparison</li><li>Kaggle submission Score</li><li>A final pipeline of the problem</li><li>Conclusion</li><li>Future Work</li><li>References</li><li>GitHub Repo</li></ol><h4><strong>Prerequisite</strong></h4><p>You have to have knowledge about the machine learning algorithms, and a little bit about the time series, and feature engineering techniques.</p><h3>1. Introduction</h3><p>Forecasting earthquakes is one of the most important problems in Earth science because of their devastating consequences. Current scientific studies related to earthquake forecasting focus on three key points: when the event will occur, where it will occur, and how large it will be. And the reason the earthquake occurs is the rupture of the geological faults but also by the other event such as volcanic activity, landslides, mine blasts, the nuclear test, etc.</p><p>So if we predict the earthquake before the time this is very helpful for the people and we can save a life of people and animals.</p><h3><strong>2. Business problem</strong></h3><p>The goal of this competition is to use seismic signals to predict the timing of laboratory earthquakes.</p><p>Here we have to predict the remaining time before the next laboratory earthquakes based on the seismic data. The remaining time is meant by the remaining time between the current earthquake and the occurrence of the next earthquake.</p><p>Since the seismic data is continuous and the real values and our target is also real value, so this is a regression problem.</p><h3><strong>3. Source of data</strong></h3><p>LANL Earthquake Prediction is a competition held by the Department of Physics &amp; Astronomy of the pursue university and hosted on the <a href="https://www.kaggle.com/c/LANL-Earthquake-Prediction">Kaggle</a>. The data set contains only two columns.</p><p><strong>The <em>dataset</em> folder contains the following files:</strong></p><ul><li><strong>Train.csv </strong>this file contains 2 columns and 629 million rows, the 1st one is <strong>acoustic_data</strong> which is a wave. this wave looks like sound waves &amp; continuous segments of experimental data. And 2nd one is <strong>time_to_failure</strong>, basically, it is the remaining time before the next earthquake.</li><li><strong>Test.csv</strong>, in this folder there are many .csv files available and each file contains a series of acoustic waves, and each test file in the test set contains only 150,000 rows of acoustic waves.</li><li><strong>Sample_submission.csv</strong>, It is of shape 2624 x 2 which has seg_id and time_to_failure,</li><li>Dataset Overview can be found in this <a href="https://www.kaggle.com/c/LANL-Earthquake-Prediction">link</a>.</li></ul><h3>4. Business constraints</h3><ol><li>The predicted value should be the Whole Number.</li><li>Strict latency constraints.</li><li>Incorrect forecasting may lead to missed loss of human, and animal life, and money.</li></ol><h3>5. Performance metrics</h3><p>The performance metric we used for the evaluation is the Mean Absolute Error (MAE) between the Predicted and actual remaining time.</p><p>In statistics, <strong>mean absolute error</strong> (<strong>MAE</strong>) is a measure of errors between paired observations expressing the same phenomenon(Wikipedia).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*T4umwffli9bpaeO3.jpg" /><figcaption><a href="https://stackoverflow.com/questions/56401346/mean-absolute-error-in-tensorflow-without-built-in-functions">Source</a></figcaption></figure><p>We also used evaluation matrice as Mean Absolute Percentage Error(MAPE).</p><h3>6. Using of machine learning</h3><p>As we know given the signal waves we have to predict the remaining time, But data is generated in the laboratory and the signal continues, so this problem is a time-series-based problem,</p><h4>Brief intro about the Time Series</h4><ol><li><strong>Univariate Time Series, </strong>It means when you want to do something forecasting based on a single variable it’s called univariate time series. Eg earthquake prediction. And handle the univariate time series we have some good models like ARIMA, Facebook Prophet, etc. we learn all models later in this notebook.</li><li><strong>Multivariate Time Series,</strong> It means when you have more than two features and predict the variables based on other features it is called a multivariable time series, Eg when you have features like Date, Humidity, rainfall and you want to predict the Temputer based on other features, it’s become multivariate time series problem.</li></ol><p>There is a different types of models for both time-series data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*HduZ1OrWrPCn1a9C" /><figcaption>Time-series Models</figcaption></figure><p>And our target value is time so these are real values hence this is a regression-based problem.</p><h3>7. Existing approaches</h3><p><strong>Solution 1</strong></p><p><a href="https://medium.com/@saivenkat_/a-detailed-case-study-on-lanl-earthquake-prediction-using-machine-learning-algorithms-beginner-to-9b38ef270887">A Detailed Case Study on LANL Earthquake Prediction using Machine Learning Algorithms-Beginner to…</a></p><p><strong>Observations</strong></p><ol><li>Here they started with how to create the new feature and some EDA parts.</li><li>In EDA they found the maximum remaining time is 16 sec and this data set contains the 16 earthquakes.</li><li>Modeling: they have used statistical models</li></ol><ul><li>SVR</li><li>XGBoost</li><li>Random Forest</li><li>Catboost</li></ul><p>4. Feature: they have used rolling window-based feature engineering.</p><p><strong>Solution 2</strong></p><p><a href="https://medium.com/@ph_singer/1st-place-in-kaggle-lanl-earthquake-prediction-competition-15a1137c2457">1st place in Kaggle LANL Earthquake Prediction Competition</a></p><p><strong>Observations</strong></p><ol><li>This blog is written by the 1st place holder of this competition.</li><li>First, they talked about features and acoustic signal manipulation.</li></ol><ul><li>In the above solution, they mention they create a statistical feature like mean, std-dev, max, etc. but the signal had a certain time-trend that caused some issues specifically on mean and quantile based features.</li><li>To overcome this issue their team add some error values in the acoustic signal and manipulate the data.</li></ul><p>3. Here they apply an (i) LGB, (ii) SVR, models and got a very high MAE.</p><h3>8. Improvements</h3><p>The biggest challenge for me in this competition problem is computational Power because we have 629 million rows, and the size of the dataset is roughly 10 GB. To overcome this problem I used the Dask library to load the data and perform the EDA, FE, and Modeling.</p><p>I spend more time in the feature engineering part, by doing basic statistical feature engineering like mean, median, max, min, etc. but my MAE and MAPE are not improving very much.</p><p>Then I come up with one good technique which is a spectrogram image, A <strong>spectrogram is</strong> <strong>a visual way of representing the signal strength, or “loudness”, of a signal over time at various frequencies present in a particular waveform</strong>.</p><p>Spectrograms are basically two-dimensional graphs, with a third dimension represented by colors. For more about spectrogram <a href="https://pnsn.org/spectrograms/what-is-a-spectrogram#:~:text=A%20spectrogram%20is%20a%20visual,present%20in%20a%20particular%20waveform.">click here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*DG_AvuQyLdQTx5Nu.jpg" /><figcaption>image representation using spectrograms</figcaption></figure><p>Here X-axis is time and Y-axis is frequency, so we can use frequency as a new feature. and spectrogram is basically an image so we can use image pixels as new features and this is the improvement of this case study.</p><p>we also use a rolling window-based feature as feature engineering.</p><h3>9. Exploratory data analysis (EDA) and its observation</h3><p>EDA will help us to understand data more clearly. with the help of EDA, we can add important features using Feature Engineering techniques which helps us to decrease MAE and MAPE scores.</p><h4><strong>9.1 Load the data and visualize</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6hoBxQHsSw1ZvNag" /></figure><h4>9.2 Distribution of acoustic data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*SOOL2VqMwg5khWYK" /><figcaption>PDF of acoustic wave</figcaption></figure><p>Here we plot a distribution of the acoustic data by using only 1% of the data because the data is very huge,</p><p>By looking at the pdf of acoustic waves we can say there are many points lie between the range of -10 to 20 and here many points are values is very high like -2000 to 4000, but here we can not say clearly about data distribution, so let’s zoom the plot of the distribution of acoustic waves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*5OSBIk7yyYplRhbd" /><figcaption>PDF of acoustic wave</figcaption></figure><p>Now we take the values of acoustic waves between -30 to 30 and here also we take only 1% of the data from the total data.</p><p>Now here we clearly see the distribution and by looking at the plot we can say -10 to 20 values of acoustic wave follow a gaussian/normal distribution of data. Here most acoustic waves have a value is 8 by looking at the bin of the histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*qEvgcP7OJnHalNgEczIWGA.png" /><figcaption>Q-Q plot of acoustic wave</figcaption></figure><p>From the Q-Q plot, we can say -2 to 2 values of Acoustic wave is following gaussian distribution.</p><h4>9.3 Distribution of time to failure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZ3B__FI7g8CzAwP1m2TDg.jpeg" /><figcaption>PDF and CDF of time to failure</figcaption></figure><p>Here we plot a distribution of our target variable which is time to failure, here we take only 1% of the data and we can say from the pdf we have a very fewer amount of data we remaining time of the next earthquake is more than 15 sec.</p><p>Here we plot a CDF of time to failure data, and we can say that 80% of data remaining time of the next earthquake is less than 9 sec.</p><h4>9.4 Acoustic data + Time to failure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btwG6pvyGedc2IAbkfJSXQ.png" /><figcaption>acoustic data with time to failure</figcaption></figure><p>For the clear visualization, we take very less data for this plot.</p><p>Let’s see how both variables change over time, the orange line is the acoustic data and the blue one is the time of failure</p><p>Here we can see data in the repeating pattern of the acoustic wave and wherever the signal is maxed values this signal is earthquake point, so here we have a total of 16 earthquake signals, and with the signal wave, we also plot the remaining time before the next earthquake.</p><p>We saw all earthquakes we have some remaining time for the next earthquake, and The shortest time to failure is 1.5 seconds and the longest is around 16 seconds.</p><h4>9.5 Test Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*76o9gK9W7X1WQB-PQU3LFw.jpeg" /><figcaption>Test data distribution and simple plot</figcaption></figure><p>In the test data, we have a different CSV file and each CSV file contains 150,000 values of acoustic data (single column), Here I have plotted a one-sample file for the understanding and we also plot a distribution plot, and the distribution is very picked And the second plot we plot all Acoustic wave values.</p><h4>9.6 Dickey-Fuller Tests</h4><p>So our data is based on the time series, and to find the data is Stationary or Non-Stationary we have to perform the test,</p><p>There are many tests available to find the given data Stationary or Non-Stationary, and one of the popular tests is called the <strong>dickey fuller test</strong> or it is also called Augmented Dickey-fuller(ADF) test.</p><p><strong>A time series is set to be stationary if the statistical property does not change over time that is it’s mean and variance are constant,<br>if its mean and variance change over time that means data is non-stationary.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeqEZjd4VskbDhsvBiMeww.png" /></figure><p>Given the plot of the time to failure, we can say it is Stationary but how we can prove this.</p><p>To prove the data is Stationary or not where the ADF test comes into the picture, for any test we have the null hypothesis H0 and alternative hypothesis H1,</p><p>So in the ADF test <strong>Null hypothesis, H0 is Time Series is Non-Stationary</strong> in nature and the alternate hypothesis <strong>H1 is Time Series is Stationary</strong> in nature</p><p>To perform the ADF test we use an adfuller library and this returns three values:-</p><p>1:- ADF Statistic value, 2:-p-value, and 3:- Critical Values.</p><p>So if the <strong>ADF Statistic &lt; Critical Values then we Reject the H0</strong> which means Time Series is Non-Stationary if the <strong>ADF Statistic &gt; Critical Values then we Accept the H0</strong> which means Time Series is Non-Stationary.</p><p>Or the same things you can say using the p-values if the p-value is very very less reject the H0 and the p-value is high then accept the H0.</p><ul><li>Code snippet:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0198be22ce9a177a337b2c6f0cfd2d9/href">https://medium.com/media/a0198be22ce9a177a337b2c6f0cfd2d9/href</a></iframe><h3>10. My first cut approach to the above problem</h3><p>I decided to create the new statistical features like mean, median, quantile values, max, min, etc. our train data set contains 629 million rows, and our test data file contains 150k rows. So here I decided to take a 150k batch size of data and generate the mean, median, max, etc values from the whole data set.</p><p>Further, to create the more features I used the rolling window based feature method with the rolling window size, rolling window means we take one size of the window/gap and we roll it into our data and after this, we create the features, as eg let&#39;s suppose we take rolling size 10 that means we take 10-row gap in the data and find the mean values from the 1st sample of the data and now we have mean values of each 10-row data, using this we create the statistical feature same as above.</p><p>Then I decided to experiment with all the below models with the hyperparameter tuning:</p><p>KNN Regression, Linear Regression, Random Forest regressor, XGBoost regressor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFcWr75sX4YT2QH2r4m5kA.png" /><figcaption>With simple statistical features,</figcaption></figure><ul><li>it seems like RF, XGB + RF regressor, and XGB performs well.</li><li>So now our task is to come up with some new meaningful features using some Feature engineering techniques that will help us to improve our MAE and MAPE scores.</li></ul><h3>11. Feature engineering</h3><p>Here we create new features and also we use the old feature as well, and here we create three new datasets with feature engineering which are helpful to predict the time of failure.</p><p><strong>11.1 Spectrogram image-based feature</strong></p><p>Using the spectrogram we convert each 150k batch size of data into a spectrogram image, we take the top 500 pixel values as new features.</p><p>Now we have the simple statistical features and 500-pixel values as features, and this is our 1st dataset with feature engineering.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d2474f9efde5688800fb67a2e171d48/href">https://medium.com/media/2d2474f9efde5688800fb67a2e171d48/href</a></iframe><p><strong>11.2 Spectrogram image-based feature with 200 pixel</strong></p><p>Here we follow the same approach as above, instead of taking 500-pixel values here, I take 200-pixel values, and here I used more statistical features instead of simple statistical features, this is our 2nd data set.</p><p><a href="https://github.com/shivambaldha/LANL-Earthquake-Prediction/blob/main/Feature_Engineering%20%2B%20Modeling.ipynb">LANL-Earthquake-Prediction/Feature_Engineering + Modeling.ipynb at main · shivambaldha/LANL-Earthquake-Prediction</a></p><p><strong>11.3 Frequencies based feature</strong></p><p>As we know Spectrogram return the three values, one of them is frequency. so we use all frequencies as new features and we combine this frequency with the statistical features, this is our 3rd dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8085d75f793d5f5110fc4d07ef9bc1c/href">https://medium.com/media/a8085d75f793d5f5110fc4d07ef9bc1c/href</a></iframe><h3>12. Modeling and comparison</h3><ol><li>Now we have three different types of datasets and using all of these datasets I applied different types of models, and our goal is predict to the time to failure.</li><li>In this section, we also want to understand how our newly created features help us to improve our MAE and MAPE.</li><li>Here I apply KNN, LR, RF, and XGB models with the hyperparameters tuning, and I also tried the stacking models.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHhOOMewU5LODzRUiT1r1Q.png" /><figcaption>Comparison of all Models vs All datasets</figcaption></figure><p><strong>Observation:</strong></p><ul><li>After looking at the result I can say that the Image 500-pixel feature helps a lot to reduce MAE.</li><li>So XGBoost and Random Forest perform better. we can think of our best models, from both these we choose the XGBoost as our final model and statistical + 500-pixel as the best feature engineering.</li><li>The code is very long so <a href="https://github.com/shivambaldha/LANL-Earthquake-Prediction/blob/main/Feature_Engineering%20%2B%20Modeling.ipynb">click here</a> for the code.</li></ul><h3>13. Kaggle submission score:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROD_vajC4AzXrJ3y9axFrw.png" /><figcaption>Submission Score</figcaption></figure><p>I got a score of 2.489 MAE score which is in the top 5% on the leader board of the challenge.</p><h3>14. A final pipeline of the problem</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a13418465c3f74879886f22befc104d/href">https://medium.com/media/6a13418465c3f74879886f22befc104d/href</a></iframe><ul><li><strong>Inputs:</strong> as input, we give a .csv file that contains acoustic signal values.</li></ul><p><a href="https://drive.google.com/drive/folders/1Muc0gtL9QnFG_NyAK7VoUQgrlwRwQyy6">sample file of case study 1 - Google Drive</a></p><ul><li><strong>Output: </strong>remaining time to next earthquake in sec</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*M-3L3PxtrJVCHfrBNF1ZGQ.png" /><figcaption>Output</figcaption></figure><p><strong>Model deployed on local box (Video)</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_W1WXxQEcpI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_W1WXxQEcpI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_W1WXxQEcpI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db34af241127266204b670f8f5be67f/href">https://medium.com/media/6db34af241127266204b670f8f5be67f/href</a></iframe><p>Model deployed on the streamlit link,</p><p><a href="https://share.streamlit.io/shivambaldha/earthquake-prediction/main/app.py">https://share.streamlit.io/shivambaldha/earthquake-prediction/main/app.py</a></p><h3>15. Conclusion:</h3><ol><li>As we saw in the first cut solution, we have only one column so we have to generate more features to predict the target values.</li><li>We saw that a new feature created based on statistical values has helped a lot to improve our MAE and MAPE, eg mean, median, percentile values.</li><li>To improve the score of MAE and MAPE we come up with the new features which are image and frequency-based features.</li><li>Proper hyperparameter tunning also plays an important role to improve MAE.</li><li>We can say that the ensemble model LGBM regressor works better for this problem.</li></ol><h3>16. Future Work:</h3><ol><li>Adding new features to the model and if we more focus on the Spectrogram image feature can improve the MAE score.</li><li>If somehow we can use a univariate time series-based model to create more features it helps to improve the score.</li><li>Using the Deep Learning technique, we can improve the MAE score.</li></ol><h3>17. References:</h3><ol><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li><li><a href="https://www.pnas.org/doi/10.1073/pnas.2011362118">https://www.pnas.org/doi/10.1073/pnas.2011362118</a></li><li><a href="https://medium.com/@saivenkat_/a-detailed-case-study-on-lanl-earthquake-prediction-using-machine-learning-algorithms-beginner-to-9b38ef270887">https://medium.com/@saivenkat_/a-detailed-case-study-on-lanl-earthquake-prediction-using-machine-learning-algorithms-beginner-to-9b38ef270887</a></li><li><a href="https://medium.com/@ph_singer/1st-place-in-kaggle-lanl-earthquakeprediction-competition-15a1137c2457">https://medium.com/@ph_singer/1st-place-in-kaggle-lanl-earthquakeprediction-competition-15a1137c2457</a></li><li><a href="https://www.youtube.com/watch?time_continue=228&amp;v=s8Q_orF4tcI&amp;feature">https://www.youtube.com/watch?time_continue=228&amp;v=s8Q_orF4tcI&amp;feature</a> =emb_title</li><li><a href="https://www.analyticsvidhya.com/blog/2019/12/6-powerful-featureengineering-techniques-time-series/">https://www.analyticsvidhya.com/blog/2019/12/6-powerful-featureengineering-techniques-time-series/</a></li><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7435601/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7435601/</a> Here this article explains the various type of features and one of them is a statistical feature.</li><li><a href="https://www.kaggle.com/code/thebrownviking20/everything-you-can-do-with-a-time-series/notebook">https://www.kaggle.com/code/thebrownviking20/everything-you-can-do-with-a-time-series/notebook</a> Here this blog explains all types of time series techniques.</li><li><a href="https://share.streamlit.io/">https://share.streamlit.io/</a> use for the deploy the model.</li></ol><h3>18. GitHub Repo</h3><p><a href="https://github.com/shivambaldha/LANL-Earthquake-Prediction">GitHub - shivambaldha/LANL-Earthquake-Prediction: Here we have to predict is the remaining time before the next laboratory earthquakes based on the seismic data</a></p><p><a href="https://www.linkedin.com/in/shivam-baldha/"><strong>Linkedin Profile</strong></a></p><p>That’s all…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27befe882a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>