<?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 Gayathri on Medium]]></title>
        <description><![CDATA[Stories by Gayathri on Medium]]></description>
        <link>https://medium.com/@gvgg1998?source=rss-151401788ad1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8-e2qJlRzFzCPd0c</url>
            <title>Stories by Gayathri on Medium</title>
            <link>https://medium.com/@gvgg1998?source=rss-151401788ad1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:23:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gvgg1998/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[Understanding K-Nearest Neighbors (KNN): A Step-by-Step Guide with Categorical and Numerical Data]]></title>
            <link>https://medium.com/@gvgg1998/understanding-k-nearest-neighbors-knn-a-step-by-step-guide-with-categorical-and-numerical-data-66e3ac769aac?source=rss-151401788ad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e3ac769aac</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[lazy-algorithm]]></category>
            <category><![CDATA[pattern-recognition]]></category>
            <category><![CDATA[euclidean-distance]]></category>
            <category><![CDATA[nearest-neighbors]]></category>
            <dc:creator><![CDATA[Gayathri]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 14:55:23 GMT</pubDate>
            <atom:updated>2024-12-30T14:55:23.086Z</atom:updated>
            <content:encoded><![CDATA[<p>The K-Nearest Neighbors (KNN) algorithm is a supervised machine learning method used for classification, regression, and detecting outliers. It’s easy to implement but can solve complex problems. KNN is called a “lazy” learning algorithm because it doesn’t have a training step. Instead, it uses all the data to make predictions by comparing new data points to the closest existing ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*AYSiHwSAfdPQSl6u.JPG" /></figure><p>KNN is non-parametric, meaning it doesn’t assume anything about how the data is distributed. This is useful because real-world data usually doesn’t follow strict patterns like being evenly spread or linearly separable.</p><h3>How KNN Works?</h3><p>The K-Nearest Neighbors (KNN) algorithm makes predictions by finding the ‘k’ closest data points (neighbors) to a given instance and then determining the outcome based on these neighbors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*BX2fes2sk3Zk6WBO" /></figure><p>Here’s how it works step-by-step:</p><ol><li><strong>Choose the number of neighbors (k):</strong> First, select the number of nearest neighbors you want the algorithm to consider. The value of ‘k’ can significantly affect the performance of the model, with smaller values making the algorithm more sensitive to noise and larger values leading to smoother predictions.</li><li><strong>Calculate the distance:</strong> For each new data point, KNN calculates the distance to all other points in the dataset. Common distance metrics include <strong>Euclidean distance</strong> (for continuous features), <strong>Manhattan distance</strong>, or <strong>Hamming distance</strong> (for categorical features).</li><li><strong>Find the k nearest neighbors:</strong> Once the distances are computed, the algorithm identifies the ‘k’ data points that are closest to the new instance.</li><li><strong>Make a prediction:</strong></li></ol><ul><li><strong>For classification:</strong> The algorithm assigns the class that is most frequent among the k-nearest neighbors (majority voting).</li><li><strong>For regression:</strong> The algorithm takes the average (or sometimes the weighted average) of the values of the k-nearest neighbors to predict the outcome.</li></ul><p><strong>5 . Decision rule:</strong> Finally, the new data point is classified (or regressed) based on the majority class or the average value of its nearest neighbors.</p><p>Here’s how you can continue with an example using categorical data, illustrating both classification and regression using KNN and Euclidean distance.</p><h3>Example of KNN Using Euclidean Distance</h3><p>Let’s now explore how KNN can work with categorical data. For simplicity, we’ll use a dataset with 7 rows where the features are a combination of numeric and categorical variables. We’ll demonstrate both classification and regression tasks.</p><h3>Dataset</h3><p>Here’s a dataset with two features, one numeric (Feature1) and one categorical (Feature2), and the target column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*AimLdLQZg6Zrz23UblS_Dg.png" /></figure><p>Suppose we have a new data point with Feature1 = 5 and Feature2 = Blue. <strong>We want to predict its class (for classification) or its value (for regression).</strong></p><h3>Solution:</h3><p><strong>Step 1 :-</strong><em> </em>Encoding Categorical Data</p><p>For categorical features, we use <strong>one-hot encoding</strong>. This is generally a better approach for categorical data in KNN because it avoids creating an artificial ordinal relationship between categories. For example, Feature2 could be transformed into three features: Red, Blue, and Green:</p><ul><li>Red = [1, 0, 0]</li><li>Blue = [0, 1, 0]</li><li>Green = [0, 0, 1]</li></ul><p>This way, the categories are treated equally in distance calculations.</p><p><strong>Step 2 :</strong>- Scaling Data</p><p>Scaling is crucial for KNN, especially when the features have different ranges. Without scaling, larger numeric ranges can dominate the distance calculations, leading to bias in the model.</p><p>Calculate the scaling for <strong>Data Point 1</strong> from the table , specifically for <strong>Feature1</strong>. We’ll use Min-Max scaling, which is done using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*AOpu0M4cH5fY-bkd8eJxJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*6YIy2vJ4RxkDgLE7GWsQPA.png" /></figure><p>So, the scaled value of <strong>Feature1</strong> for Data Point 1 is <strong>0</strong>. Repeat the process for the remaining dataset.</p><p>Let’s quickly modify the given dataset using one-hot encoding and scaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*weLqkzpG232Q8hUld2ORGw.png" /></figure><p><strong>step 3 :-</strong> Preparing the New Data Point</p><p>For the new data point (Feature1 = 5, Feature2 = Blue), after encoding and scaling, it becomes:</p><p>New Data Point=[0.5,0,1,0]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Vfc-Dg-x3fxZq5qRtjw-Zg.png" /></figure><p><strong>Step 4 :-</strong> Calculate Euclidean Distance</p><p>Now we compute the Euclidean distance between the new data point and all the existing data points in the dataset. The Euclidean distance formula for two points (x1,y1,z1)and (x2,y2,z2) in 3D is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*aIgoiofuj9oUUStbxnHipw.png" /><figcaption>Euclidean distance</figcaption></figure><p>Distance Calculations : Let’s calculate the Euclidean distance from the new data point [0.5,0,1,0] to each data point in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*L1Bc4OastIMfRnNk0wI_7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*vsUuZb0LdKrKk6btEJh0dQ.png" /></figure><p><strong>Step 5</strong>:- Find the Nearest Neighbors</p><p>Assuming k = 3 (i.e., we want the 3 nearest neighbors), we can now select the 3 smallest distances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*bdh3JHHOYa4Rk-1Gt-Gh2Q.png" /></figure><p>finally, prediction for a new data point with Feature1 = 5 and Feature2 = Blue.</p><p>a)For classification: we look at the classes of the 3 nearest neighbors, using majority voting, the predicted class is <strong>B</strong>.</p><p>b) For Regression: we take the average of the target values (for regression) of the 3 nearest neighbors:</p><ul><li><em>Data Point 2:</em> Regression Target = 2.0</li><li><em>Data Point 4: </em>Regression Target = 3.8</li><li><em>Data Point 7: </em>Regression Target = 5.5</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*t5sr96ly2qqCuYjDfJTYKQ.png" /></figure><p>we successfully applied the K-Nearest Neighbors (KNN) algorithm to predict the class and value for a new data point with Feature1 = 5 and Feature2 = Blue.</p><h3>Conclusion:</h3><p>The K-Nearest Neighbors (KNN) algorithm is a simple yet effective tool for solving both classification and regression problems, especially when dealing with mixed datasets. We’ve explored how KNN works with categorical and numerical data and how proper encoding and scaling are crucial for accurate predictions. While easy to implement, KNN requires thoughtful data preprocessing and parameter selection to perform well in real-world scenarios. With careful handling of distance metrics and data, KNN remains a powerful algorithm in the machine learning toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e3ac769aac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Naive Bayes: A Simple Yet Powerful Classifier]]></title>
            <link>https://medium.com/@gvgg1998/demystifying-naive-bayes-a-simple-yet-powerful-classifier-f0410da4267e?source=rss-151401788ad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0410da4267e</guid>
            <category><![CDATA[bayes-theorem]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[naive-bayes-algorithm]]></category>
            <category><![CDATA[gaussian-naive-bayes]]></category>
            <category><![CDATA[naive-bayes-classifier]]></category>
            <dc:creator><![CDATA[Gayathri]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 16:24:25 GMT</pubDate>
            <atom:updated>2024-11-14T16:24:25.675Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Exploring Naive Bayes: How It Works, Math Behind Naive Bayes, Advantages and Disadvantages</em></p><p><strong>Introduction to Naive Bayes:</strong></p><p>Naive Bayes is a simple yet effective algorithm for classification tasks, widely used in areas like spam detection and text classification. Based on <strong>Bayes’ Theorem</strong>, it calculates the probability of an outcome given prior information. The “naive” assumption that all features are independent makes it computationally efficient, even with large datasets. Despite this assumption rarely holding true in practice, Naive Bayes performs well in many real-world applications. It’s fast, easy to implement, and often used as a baseline model in classification problems.</p><h3><strong>The Math Behind Naive Bayes</strong>:</h3><p><strong>Bayes’ Theorem</strong> is the foundation of Naive Bayes algorithms. It describes the probability of an event, based on prior knowledge of conditions related to the event. In simple terms, it helps us update our beliefs or predictions based on new data.</p><p>The theorem can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*6D_A5tBI57CMWdBjYfxOtg.png" /></figure><ul><li><strong>Posterior Probability</strong>: P(A∣B)— The probability of event A happening, given that B has occurred.</li><li><strong>Likelihood</strong>: P(B∣A) — The probability of event B happening, given that A has occurred.</li><li><strong>Prior Probability</strong>: P(A) — The initial probability of event A happening.</li><li><strong>Evidence</strong>: P(B)— The total probability of event B happening.</li></ul><p>In Naive Bayes, Bayes’ Theorem is applied to classify data by calculating the posterior probability of a class label given the input features. Despite its simplicity, it works well in many real-world scenarios.</p><h3>How Naive Bayes Works?</h3><p>Naive Bayes is based on Bayes’ Theorem, and it classifies data by calculating the probability of different classes for a given input. Here’s a breakdown of how it works:</p><h4>Step-by-Step Process:</h4><p><strong>Training Phase</strong>:</p><ol><li><strong>Calculate Prior Probabilities</strong>:</li></ol><ul><li>For each class in the training data (e.g., “spam” or “not spam”), calculate the prior probability by dividing the number of instances of that class by the total number of instances.</li><li>Example: If 30% of the emails in the training set are spam, the prior probability for “spam” is 0.3.</li></ul><p><strong>2. Calculate Likelihoods</strong>:</p><ul><li>For each feature (like words in an email), calculate the likelihood that the feature occurs in each class.</li><li>Example: If the word “offer” appears in 50% of spam emails and 5% of non-spam emails, the likelihoods for “offer” would be 0.5 (spam) and 0.05 (not spam).</li></ul><p><strong>Prediction Phase</strong>:</p><p><strong>3. Calculate Posterior Probabilities</strong>:</p><ul><li>For a new instance (like an email), calculate the posterior probability of each class by multiplying the prior probability of the class by the likelihood of the features, using Bayes’ Theorem.</li><li>Example: Given an email with words “win” and “offer”, multiply the likelihoods of these words occurring in each class with the prior for each class.</li></ul><p><strong>4. Assign Class</strong>:</p><ul><li>The class with the highest posterior probability is selected as the predicted class for the instance.</li><li>If the probability of the email being “spam” is higher than “not spam,” it is classified as “spam.”</li></ul><h4>Simple Example:</h4><p>Let’s say you want to classify an email as spam or not spam based on the words “win” and “offer.”</p><ol><li><strong>Prior Probabilities</strong>:</li></ol><blockquote>P(Spam) = 0.3 (30% of emails are spam)</blockquote><blockquote>P(Not Spam) = 0.7 (70% of emails are not spam)</blockquote><p><strong>2 . Likelihoods</strong>:</p><blockquote>P(“win” | Spam) = 0.6, P(“win” | Not Spam) = 0.1</blockquote><blockquote>P(“offer” | Spam) = 0.5, P(“offer” | Not Spam) = 0.05</blockquote><p><strong>3. Posterior Calculation</strong>:</p><blockquote><strong>For Spam:</strong></blockquote><blockquote>P(Spam | “win”, “offer”) = P(Spam) * P(“win” | Spam) * P(“offer” | Spam) = 0.3 * 0.6 * 0.5 = 0.09</blockquote><blockquote><strong>For Not Spam:</strong></blockquote><blockquote>P(Not Spam | “win”, “offer”) = P(Not Spam) * P(“win” | Not Spam) * P(“offer” | Not Spam) = 0.7 * 0.1 * 0.05 = 0.0035</blockquote><p><strong>4. Prediction</strong>:</p><blockquote>Since 0.09 (Spam) &gt; 0.0035 (Not Spam), the email is classified as <strong>Spam</strong>.</blockquote><p>This process illustrates how Naive Bayes uses probabilities to make predictions by combining prior knowledge (the prior probability) with new data (likelihoods of the features).</p><h3>Python Code Example: Spam Classification Using Gaussian Naive Bayes<strong>:</strong></h3><p>In this example, we’ll use the Gaussian Naive Bayes model, which is suitable for continuous data. We’ll simulate some numerical features for emails, such as the number of exclamation marks, email length, and whether it contains certain spammy words.</p><blockquote># Import necessary libraries</blockquote><blockquote>import numpy as np</blockquote><blockquote>import pandas as pd</blockquote><blockquote>from sklearn.model_selection import train_test_split</blockquote><blockquote>from sklearn.naive_bayes import GaussianNB</blockquote><blockquote>from sklearn.metrics import accuracy_score, classification_report</blockquote><p>Here’s a quick look at the dataset we’ll use for this example. It includes three features:</p><ul><li><strong>exclamation_marks</strong>: Number of exclamation marks in the email.</li><li><strong>email_length</strong>: Length of the email in characters.</li><li><strong>contains_spam_words</strong>: Whether or not the email contains words commonly associated with spam (1 for yes, 0 for no). These features will help us determine the likelihood that an email is spam based on its content and structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnlT72AzYAGmLfdpCYWCqA.png" /></figure><p>With our dataset prepared, we proceed to create a Gaussian Naive Bayes model. This algorithm works well for continuous data and assumes a Gaussian (normal) distribution for each feature. Here’s a breakdown of our process:</p><ul><li><strong>Data Splitting</strong>: We split the data into training and test sets to evaluate model accuracy.</li><li><strong>Model Training</strong>: The model is trained using the training data, where it learns to associate certain features with either the “spam” or “not spam” class.</li><li><strong>Model Testing</strong>: After training, we use the test set to see how accurately the model predicts whether a new email is spam.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*SSNzxGkK6hN7RSPFOdNSKA.png" /></figure><p>Finally, we evaluate the model’s performance by calculating accuracy and generating a classification report. This gives us a clear picture of how well the model distinguishes between spam and non-spam emails.</p><h3>Types of Naive Bayes Algorithms:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*cjxGhoUWygxXs9dbW2NXpA.png" /></figure><h3>Advantages and Disadvantages of Naive Bayes</h3><h4>Advantages:</h4><ol><li><strong>Simplicity</strong>: Naive Bayes is easy to understand and implement due to its straightforward probabilistic approach.</li><li><strong>Fast</strong>: It requires less computational power, making it efficient even for large datasets.</li><li><strong>Works Well with Small Data</strong>: Naive Bayes can perform well even with smaller datasets.</li><li><strong>Handles High-Dimensional Data</strong>: It can handle a large number of features, especially in text classification tasks.</li><li><strong>Robust to Irrelevant Features</strong>: The algorithm is relatively unaffected by the presence of irrelevant features.</li><li><strong>Handles Missing Data</strong>: Naive Bayes can handle missing data by ignoring it during training, unlike other algorithms that require data imputation.</li></ol><h4>Disadvantages:</h4><ol><li><strong>Assumption of Feature Independence</strong>: Naive Bayes assumes that all features are independent of each other, which is rarely true in real-world data.</li><li><strong>Sensitive to Data Distribution</strong>: It assumes a normal distribution for continuous features (in the case of GaussianNB), which may not hold true.</li><li><strong>Limited with Complex Models</strong>: Naive Bayes might not perform well when more complex relationships between features exist, as it doesn’t capture feature interactions.</li><li><strong>Class Imbalance</strong>: It can struggle when the data is highly imbalanced, often predicting the majority class more frequently.</li><li><strong>Not Suitable for Regression</strong>: Naive Bayes is strictly a classification algorithm and cannot be used for regression tasks.</li></ol><h3>Applications of Naive Bayes</h3><ol><li><strong>Text Classification</strong>:</li></ol><ul><li>Commonly used in <strong>spam detection</strong> (e.g., classifying emails as spam or not).</li><li>Employed for <strong>sentiment analysis</strong> to determine if a review or text is positive or negative.</li><li>Document categorization, where text is classified into predefined categories like sports, politics, etc.</li></ul><p><strong>2 . Medical Diagnosis</strong>:</p><ul><li>Naive Bayes is used to predict diseases based on symptoms and medical data (e.g., diagnosing heart disease or cancer risk).</li></ul><p><strong>3 . Customer Segmentation</strong>:</p><ul><li>Useful for segmenting customers based on demographic information (e.g., age, gender) and predicting customer behavior.</li></ul><p><strong>4 . Recommender Systems</strong>:</p><ul><li>Naive Bayes can be used in recommender systems to predict user preferences and suggest products or services based on past behavior.</li></ul><p><strong>5. Fraud Detection</strong>:</p><ul><li>Applied in fraud detection systems to classify transactions as fraudulent or legitimate by analyzing patterns in the data.</li></ul><p><strong>6. Real-Time Prediction</strong>:</p><ul><li>Due to its speed and efficiency, Naive Bayes is often used in real-time applications, such as social media monitoring or real-time bidding systems.</li></ul><h3>Conclusion :</h3><p>Naive Bayes is a powerful tool for classification when speed and simplicity are essential. It performs well in spam detection, sentiment analysis, and text classification, especially with large datasets. Although it assumes feature independence (a limitation for more complex tasks), Naive Bayes remains an efficient and reliable choice for many classification problems. For highly correlated features, models like logistic regression or decision trees may be more effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0410da4267e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models with FastAPI and Docker: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@gvgg1998/deploying-machine-learning-models-with-fastapi-and-docker-a-step-by-step-guide-5e35b984f792?source=rss-151401788ad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e35b984f792</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ml-deployment]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Gayathri]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 17:31:36 GMT</pubDate>
            <atom:updated>2024-09-15T17:31:54.631Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, deploying machine learning (ML) models efficiently is critical for making solutions accessible and scalable. While model development is essential, ensuring that models are deployed in production environments where they can be accessed by applications is equally important.</p><p>In this article, I’ll walk you through how to deploy an ML model using FastAPI, a modern Python web framework for building APIs, and Docker, a tool that helps package and run applications in containers, ensuring smooth operation in any environment.</p><p>We’ll start by building a simple ML model API using FastAPI, and then package the entire application using Docker for easy deployment. By the end, you’ll be equipped to deploy your own ML models in production environments.</p><h3>Step 1: Preparing the Machine Learning Model</h3><p>Before deploying a model, you need to have a trained machine-learning model ready for production. In my case, I’ve built a sales prediction model using the Jupyter note book. Once the model is trained, we save it using joblib or pickle for later use in our FastAPI application. Below is the code snippet for saving the model:</p><p><em>import joblib<br>joblib.dump(model_pipeline, ‘big_market_sales_prediction.pkl’)</em></p><p>This will create a big_market_sales_prediction.pkl file in the same directory where you have your ML model.</p><p><strong>Folder Structure</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*wT_Oua3MY5EPMz6sJzVIYw.png" /></figure><ul><li>sales_prediction.ipynb: Jupyter notebook containing the model.</li><li>big_market_sales_prediction.pkl: Pickle file with the saved model.</li></ul><h3>Step 2: Setting Up FastAPI</h3><h4>1. Create a FastAPI Application</h4><p>To serve your model, we’ll use FastAPI to create an API that can take in data, make predictions, and return results. Here’s how to set up the FastAPI application.</p><ul><li>Create a Python file named fastapi_model.py.</li><li>Import the necessary packages:</li></ul><p><em>from fastapi import FastAPI<br>from pydantic import BaseModel<br>import pandas as pd<br>import joblib</em></p><h4>2. Define Input and Output Models</h4><p>Using Pydantic’s BaseModel, we can define the structure of the input data that the model will accept and the format of the response.</p><p><em>class Input(BaseModel):<br> Item_Identifier: str</em><br> <em>Item_Weight: float<br> Item_Fat_Content: str<br> Item_Visibility: float<br> Item_Type: str<br> Item_MRP: float<br> Outlet_Identifier: str<br> Outlet_Establishment_Year: int<br> Outlet_Size: str<br> Outlet_Location_Type: str<br> Outlet_Type: str</em></p><p><em>class Output(BaseModel):<br> y: float</em></p><h4>3. Create the Prediction Endpoint</h4><p>The API will accept POST requests at /predict, which takes in the input features and returns the model’s prediction. Below is the implementation:</p><p><em>app = FastAPI()</em></p><p><a href="http://twitter.com/app"><em>@app</em></a><em>.post(“/predict”)<br>def predict(data: Input) -&gt; Output:<br> # Convert input data to a dictionary, then to a DataFrame<br> input_dict = {<br> ‘Item_Identifier’: [data.Item_Identifier],<br> ‘Item_Weight’: [data.Item_Weight],<br> ‘Item_Fat_Content’: [data.Item_Fat_Content],<br> ‘Item_Visibility’: [data.Item_Visibility],<br> ‘Item_Type’: [data.Item_Type],<br> ‘Item_MRP’: [data.Item_MRP],<br> ‘Outlet_Identifier’: [data.Outlet_Identifier],<br> ‘Outlet_Establishment_Year’: [data.Outlet_Establishment_Year],<br> ‘Outlet_Size’: [data.Outlet_Size],<br> ‘Outlet_Location_Type’: [data.Outlet_Location_Type],<br> ‘Outlet_Type’: [data.Outlet_Type]<br> }</em></p><p><em>X_input = pd.DataFrame(input_dict)</em></p><p><em># Load the pre-trained model<br> model = joblib.load(‘big_market_sales_prediction.pkl’)</em></p><p><em># Make prediction<br> prediction = model.predict(X_input)<br> <br> return {“y”: prediction[0]}</em></p><h4>4. Run the FastAPI Application</h4><p>Run your FastAPI application with the following command:</p><blockquote>uvicorn fastapi_model:app — host 127.0.0.1 — port 8080 — reload</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*HdGHM9gEpsBjmH-qfy_NkA.png" /></figure><p>Open the following URL in your browser: http://127.0.0.1:8080/docs. This will lead you to the Swagger UI, which displays the API endpoints you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9uyIM04mTL_g0uYk2Q_GA.png" /></figure><p>If you’re satisfied running this locally, you can stop here. However, if you’d like to deploy this through Docker, continue with the next steps.</p><h3>Step 3: Containerizing with Docker</h3><p>Docker allows us to bundle the application, its dependencies, and environment configurations in a container that can run on any platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*biNlUbmnXpc2L7yud3K-fw.png" /></figure><h4>1. Create a requirements.txt File</h4><p>This file lists all the necessary dependencies for your FastAPI app. Here’s an example:</p><p><em>pandas<br>fastapi<br>uvicorn<br>numpy<br>pydantic<br>joblib<br>scikit-learn</em></p><h4>2. Create a Dockerfile</h4><p>This Dockerfile defines the environment and instructions to build the container. Here’s what each line does:</p><p><em># Start with an official Python image<br>FROM python:3.9-slim</em></p><p><em># Set working directory in the container<br>WORKDIR /app</em></p><p><em># Copy all files from the current directory to /app in the container<br>COPY . /app</em></p><p><em># Install dependencies<br>RUN pip install -r requirement.txt</em></p><p><em># Expose port 80 for the application<br>EXPOSE 80</em></p><p><em># Define the command to run the FastAPI app using uvicorn<br>CMD [“uvicorn”, “fastapi_model:app”, “ — host”, “0.0.0.0”, “ — port”, “80”]</em></p><h4>3. Build and Run the Docker Container</h4><ul><li><strong>Build the Docker image</strong>: Run the following command to build the image and tag it as fastapi-docker.</li></ul><blockquote>docker build -t fastapi-docker .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7G3TrJQZu_z78tyagzK1w.png" /></figure><p><strong>Run the Docker container</strong>: After building the image, you can run the container and map it to port 8080 on your local machine.</p><blockquote>docker run -p 8080:80 fastapi-docker</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*6kEKaqd4g3K3BGQnCRayAQ.png" /></figure><p>Now, open http://localhost:8080 in your browser to access the FastAPI app. If you want to share access with others on the same network, they can use your machine’s IP address: http://&lt;your-ip-address&gt;:8080.</p><p>To push your Docker image to a Docker repository (such as Docker Hub), follow these steps:</p><h3>Step 4: Pushing to Docker Hub</h3><ol><li><strong>Login to Docker Hub</strong>: First, log in to your Docker Hub account.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*um0Z3OpEppgb_InRmrRA9Q.png" /></figure><p>2. <strong>Tag the Image</strong>: Before pushing the image, tag it with your Docker Hub repository name.</p><blockquote>docker tag &lt;image_name&gt; &lt;dockerhub_username&gt;/&lt;repository_name&gt;:&lt;tag&gt;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*89aLCJgRmqonpHULz1KsgQ.png" /></figure><p><strong>3. Push the Image</strong>: Push the tagged image to Docker Hub.</p><blockquote>docker push &lt;dockerhub_username&gt;/&lt;repository_name&gt;:&lt;tag&gt;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*FyR2Tg0NE4j29fRzlRQ0HQ.png" /></figure><p><strong>Verify the Push</strong>: You can verify that the image is successfully pushed by logging into your Docker Hub account and checking the repository.</p><h3>Conclusion</h3><p>By following this guide, you’ve successfully deployed an ML model using FastAPI and Docker. This setup allows for fast, scalable deployment of your machine learning models in production environments. You can now integrate your API with any front-end application or system, and Docker ensures that your solution will work regardless of the environment.</p><h3>Check Out the Full Code on GitHub</h3><p>If you’d like to explore the complete code for this project, you can find it on my GitHub repository. Feel free to clone the project, experiment with it, and modify it as needed.</p><p>GitHub Repository: <a href="https://github.com/Gayathrigopi98/Fastapi-and-Docker">https://github.com/Gayathrigopi98/Fastapi-and-Docker</a></p><p>I hope this guide helps you in deploying your machine learning models using FastAPI and Docker. If you have any questions or suggestions, feel free to reach out or open an issue on GitHub!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e35b984f792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Evaluation of Linear Regression Models with Error Metrics]]></title>
            <link>https://medium.com/@gvgg1998/comprehensive-evaluation-of-linear-regression-models-with-error-metrics-839c6f383797?source=rss-151401788ad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/839c6f383797</guid>
            <category><![CDATA[r-squared]]></category>
            <category><![CDATA[root-mean-squared-error]]></category>
            <category><![CDATA[mean-absolute-error]]></category>
            <category><![CDATA[mean-squared-error]]></category>
            <category><![CDATA[error-metrics]]></category>
            <dc:creator><![CDATA[Gayathri]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 13:16:48 GMT</pubDate>
            <atom:updated>2024-12-30T14:02:08.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear regression is a supervised machine learning algorithm that models the relationship between a dependent variable and one or more independent features using a linear equation.</p><p><strong>Simple Linear Regression</strong>: Involves one independent feature and one dependent variable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SnbJhXG60VGugThGzrEYw.png" /></figure><p><strong>Multiple Linear Regression</strong>: Involves multiple independent features and one dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQV99xfe0Im5s7UFF_T49g.png" /></figure><p><strong>Best-Fit Line</strong></p><p>A crucial aspect of linear regression is determining the best-fit line, which best represents the relationship between the independent variable(s) and the dependent variable. This line is positioned to closely approximate the actual data points, making it easier to understand and predict the dependent variable’s behaviour based on the independent variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*DoouPZmLl8D2FxH9bhrvtw.png" /></figure><p><strong>Introduction to Error Metrics</strong></p><p>Once a linear regression model is created, it’s essential to evaluate how well it performs. This is where error metrics come into play. These metrics measure the accuracy of the model’s predictions compared to the actual values. Understanding these metrics is key to refining the model, comparing it with others, and improving its predictive accuracy.</p><p>Common Error Metrics Include:</p><p><strong>Mean Absolute Error (MAE):</strong></p><p>MAE gives the average of absolute errors, treating all errors equally without regard to their direction (overprediction or underprediction). It’s straightforward and interpretable. MAE is calculated using the following formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*5fgOD0c95FGOSLFXD5w3Sg.png" /></figure><p>Let’s go through an example to see how this metric works in practice.</p><p>Example Scenario : Imagine you are building a linear regression model to predict the daily maximum temperature (in degrees Celsius) based on various weather features. After training your model, you test it on five days and get the following actual and predicted temperatures:</p><ul><li><strong>Day 1:</strong> Actual = 30°C, Predicted = 32°C</li><li><strong>Day 2:</strong> Actual = 25°C, Predicted = 28°C</li><li><strong>Day 3:</strong> Actual = 35°C, Predicted = 33°C</li><li><strong>Day 4:</strong> Actual = 28°C, Predicted = 29°C</li><li><strong>Day 5:</strong> Actual = 31°C, Predicted = 30°C</li></ul><p><strong>Calculation:</strong></p><ul><li>Compute the absolute errors: ∣30−32∣,∣25−28∣,∣35−33∣,∣28−29∣,∣31−30∣.</li><li>Absolute errors are: 2°C, 3°C, 2°C, 1°C, 1°C.</li><li>Average these errors: MAE=(2+3+2+1+1)/5 = 1.8°C</li></ul><p><strong>Interpretation:</strong> On average, the model’s predictions are off by 1.8°C from the actual temperatures</p><p><strong>Mean Squared Error (MSE):</strong></p><p>MSE squares the errors before averaging, thus giving more weight to larger errors. It’s useful when large errors are particularly undesirable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*9E_qyALNhHrWAx1gzuPaSQ.png" /></figure><p>Continuing with the previous scenario:</p><p><strong>Example Calculation:</strong></p><ul><li>Square the errors: 2²,3²,2²,1²,1²</li><li>Squared errors are: 4, 9, 4, 1, 1.</li><li>Average these squared errors: (4+9+4+1+1)/5 = 3.8 °C</li><li><strong>Interpretation:</strong> The average of the squared errors is 3.8°C, emphasizing larger errors more due to the squaring.</li></ul><p><strong>Root Mean Squared Error (RMSE):</strong></p><p>RMSE is the square root of MSE, translating the metric back into the same units as the dependent variable. It balances the penalization of large errors with interpretability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*wxqVPXaTalPYwPCJyZzrfw.png" /></figure><p>Using the MSE calculated above:</p><ul><li>Take the square root of the MSE:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*elZRIExGBku6hYsfs1oapA.png" /></figure><ul><li><strong>Interpretation:</strong> The RMSE of 1.95°C provides an error measure that’s in the same units as the temperature, balancing sensitivity to larger errors with interpretability.</li></ul><p><strong>R-Squared (R²):</strong></p><p>R² represents the proportion of variance in the dependent variable that is predictable from the independent variables. A higher R² indicates a better fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*2ebu7XfkPUD_P6bSuJITyg.png" /></figure><p>Using the same scenario:</p><ul><li>Let’s assume the average temperature (mean of actual temperatures) is 29.8°C.</li><li>The total variance in the actual temperatures (Total Sum of Squares) is:</li></ul><p><em>SStot</em> = ( 30–29.8)² + (25–29.8)² + (35–29.8)² + (28–29.8)² + (31–29.8)²</p><ul><li>The variance that is not explained by the model (Residual Sum of Squares) is the sum of squared errors (MSE times the number of observations): <em>SSres​=3.8×5=19</em></li><li>Compute R²: R² = 1-(19/35.2) ~ 0.46</li></ul><p><strong>Interpretation:</strong> The R²value of 0.46 indicates that the model explains 46% of the variance in the actual temperatures.</p><p><strong>Mean Absolute Percentage Error (MAPE):</strong></p><p>MAPE measures the accuracy of predictions as a percentage, which is useful for comparing models across different scales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*5oGbweFJY6frD-J6sMcqdw.png" /></figure><p>Again, using the previous scenario:</p><ul><li>Compute the percentage errors: 2/30 ,3/25, 2/35 , 1/28, 1/31</li><li>Percentage errors are approximately: 6.67%, 12%, 5.71%, 3.57%, 3.23%.</li><li>Average these percentages:</li></ul><p>MAPE = (6.67 + 12 + 5.71 + 3.57 + 3.23 ) / 5 ~ 6.24 %</p><ul><li><strong>Interpretation:</strong> The MAPE of 6.24% means that, on average, the model’s predictions are off by about 6.24% of the actual temperatures.</li></ul><p>To better understand the strengths and weaknesses of each error metric, the following table summarizes their advantages, disadvantages, and ideal use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GneSkdlIGHxaC_pBtUXVAA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=839c6f383797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Linear Regression Models by Understanding Key Assumptions]]></title>
            <link>https://medium.com/@gvgg1998/improving-linear-regression-models-by-understanding-key-assumptions-5150a3fc19d7?source=rss-151401788ad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5150a3fc19d7</guid>
            <category><![CDATA[basic-linear-regression]]></category>
            <category><![CDATA[multicollinearity-risks]]></category>
            <category><![CDATA[homoscedasticity-check]]></category>
            <category><![CDATA[improving-model]]></category>
            <category><![CDATA[key-assumptions]]></category>
            <dc:creator><![CDATA[Gayathri]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 10:32:01 GMT</pubDate>
            <atom:updated>2024-09-10T10:32:01.683Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear regression is a widely used statistical method to understand the relationship between a dependent variable and one or more independent variables. To make sure the model provides accurate and reliable predictions, it relies on a set of key assumptions. These assumptions are important because they affect how well the model fits the data.</p><p>Since linear regression is a <strong>parametric method</strong>, it requires certain conditions to be true about the data, making it somewhat limited. When the data follows these assumptions, the model works well, but if the assumptions are not met, the model might give incorrect or misleading results.</p><p>In short, checking and validating these assumptions is essential to ensure the linear regression model delivers meaningful and trustworthy predictions.</p><p>Mainly there are 7 assumptions taken while using Linear Regression:</p><ul><li>Linearity</li><li>No Multicollinearity in the data</li><li>Homoscedasticity of Residuals or Equal Variances</li><li>No Autocorrelation in residuals</li><li>Number of observations Greater than the number of predictors</li><li>Each observation is unique</li><li>Predictors are distributed Normally</li></ul><ol><li><strong>Linearity</strong></li></ol><p>The first assumption of linear regression is that there should be a <strong>linear relationship</strong> between the independent variable(s) (x) and the dependent variable (y). This means that changes in x should lead to proportional changes in y. If the relationship is non-linear, the model’s predictions will likely be inaccurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*uM5J24og6jNZWwDlBzcBug.png" /></figure><p><strong>How to Check Linearity:</strong></p><p>· <strong>Scatter Plot:</strong> Plot x vs. y to visually check if the points form a straight line. A linear pattern confirms the assumption is met.</p><p>· <strong>Residuals vs. Fitted Plot:</strong> If the residuals are randomly scattered, the relationship is linear. A curved pattern indicates non-linearity.</p><p><strong>2. Multicollinearity:</strong></p><p>Multicollinearity happens when two or more independent variables in a model are highly correlated, meaning they provide similar information. This is a problem because it adds complexity to the model without helping it learn anything new. It becomes harder to tell which variable is actually influencing the target variable.</p><p>When multicollinearity is present, the standard errors of the coefficients increase, making the model’s predictions less reliable. The coefficients of the correlated variables can also change a lot depending on whether other variables are included, leading to wrong conclusions about their impact.</p><p><strong>How to Check for Multicollinearity:</strong></p><ul><li><strong>Scatter Plot or Heatmap:</strong> Use these to see if variables are correlated visually.</li><li><strong>Variance Inflation Factor (VIF):</strong> A VIF value less than 4 is good, while a value of 10 or more indicates serious multicollinearity.</li><li><strong>Correlation Matrix:</strong> This table shows how closely variables are related and helps spot multicollinearity.</li></ul><p><strong>3. Homoscedasticity in Linear Regression</strong></p><p>Homoscedasticity means that the residuals (errors-difference between an observed value and a predicted value) from the linear regression model should have constant variance across all levels of the independent variable(s). In other words, the spread of the residuals should be roughly the same at every level of the predicted values. If the residuals show uneven spread (heteroscedasticity), the model may be unreliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*djPEhlB5CNtR27GO49Hchg.png" /></figure><p><strong>How to Check for Homoscedasticity:</strong></p><ul><li><strong>Residuals vs. Fitted Values Plot:</strong> Create a scatter plot of residuals against the predicted values. If the points are spread evenly (no clear pattern), homoscedasticity is present. If the spread increases or decreases, this suggests heteroscedasticity, indicating a problem with the model.</li></ul><p><strong>4. No Autocorrelation in Residuals</strong></p><p>The residuals (errors) should not be correlated with each other. This means that the residuals for one observation should not predict the residuals for another observation. Autocorrelation often occurs in time series data.</p><p><strong>How to Check:</strong></p><p>· <strong>Durbin-Watson Test:</strong> A statistical test to detect autocorrelation in residuals.</p><p>· <strong>Residuals vs. Time Plot:</strong> Plot residuals against time to check for patterns or correlations.</p><p><strong>5. Number of Observations Greater than the Number of Predictors</strong></p><p>The number of observations (data points) should be greater than the number of predictors (variables). This ensures that the model has enough data to estimate the coefficients reliably.</p><p><strong>How to Check:</strong></p><p>· <strong>Data Count:</strong> Simply verify that the number of observations exceeds the number of predictors in your dataset.</p><p><strong>6. Each Observation is Unique</strong></p><p>Each observation in the dataset should be unique. Duplicate observations can skew the results and affect the model’s performance.</p><p><strong>How to Check:</strong></p><p>· <strong>Data Review:</strong> Inspect the dataset for duplicate entries and remove them if necessary.</p><p><strong>7. Predictors are Distributed Normally (for inference purposes)</strong></p><p>While not always required, normality of predictors can be important for certain inference tasks. It helps in making valid statistical inferences and hypothesis testing.</p><p><strong>How to Check:</strong></p><p>· <strong>Histogram/QQ Plot:</strong> Plot the distribution of predictors to visually inspect normality.</p><p>· <strong>Shapiro-Wilk Test:</strong> A statistical test to check for normality.</p><p><strong>Conclusion</strong></p><p>Linear regression is a powerful statistical tool, but its effectiveness hinges on several key assumptions. Ensuring these assumptions are met is crucial for generating accurate and meaningful predictions. Violations of these assumptions can lead to biased, inefficient, or misleading results. Therefore, it is essential to rigorously check these assumptions before relying on a linear regression model. By understanding and validating these assumptions, you can improve the reliability of your models and make more informed decisions based on the results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5150a3fc19d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>