<?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 Reddykowshik on Medium]]></title>
        <description><![CDATA[Stories by Reddykowshik on Medium]]></description>
        <link>https://medium.com/@reddykowshik2008?source=rss-ef562057d205------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pQa5VjHYKQrjRCIM</url>
            <title>Stories by Reddykowshik on Medium</title>
            <link>https://medium.com/@reddykowshik2008?source=rss-ef562057d205------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:12:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reddykowshik2008/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[Build a Simple ML Inference API: Turn a Machine Learning Model into a Working Application]]></title>
            <link>https://medium.com/@reddykowshik2008/build-a-simple-ml-inference-api-turn-a-machine-learning-model-into-a-working-application-56f4015b5e44?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/56f4015b5e44</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 09:09:55 GMT</pubDate>
            <atom:updated>2026-12-04T09:09:55.797Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From training a machine learning model to making predictions through a real API.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2kYGtmziOM3g-UibeXWGQ.png" /><figcaption><em>From model training to real-world predictions: building a simple ML inference API.</em></figcaption></figure><h3>Introduction</h3><p>Machine Learning models are useful because they can learn patterns from data and make predictions. However, training a model is only one part of building a complete machine learning application.</p><p>Imagine that we have trained a model that can identify different types of flowers. How can another application use this model to make predictions?</p><p>One solution is to create a <strong>Machine Learning Inference API</strong>.</p><p>An inference API allows other applications to send input data to a trained machine learning model and receive predictions through an API endpoint.</p><p>In this article, we will build a simple ML inference API using Python, Scikit-learn, FastAPI, and Joblib. We will train a Random Forest model using the Iris dataset, save it, and connect it to a FastAPI application.</p><p>By the end, we will have a working API that accepts flower measurements and predicts the flower species.</p><h3>1. What Is a Machine Learning Inference API?</h3><p>A Machine Learning Inference API is an interface that allows users or applications to access a trained machine learning model.</p><p>It receives input data, passes that data to the model, and returns the prediction.</p><p>For example:</p><ol><li>A user enters flower measurements.</li><li>The API receives those measurements.</li><li>The trained ML model analyzes the input.</li><li>The API returns the predicted flower species.</li></ol><p>This makes it possible to use a machine learning model without directly running its training code every time.</p><h3>2. Why Do We Need an ML Inference API?</h3><p>After training a machine learning model, we may want to use it in a website, mobile application, or another software system.</p><p>Without an API, connecting the model to different applications can become difficult.</p><p>An inference API provides several benefits:</p><ul><li><strong>Reusability:</strong> Different applications can use the same trained model.</li><li><strong>Integration:</strong> Models can connect with websites and mobile applications.</li><li><strong>Scalability:</strong> The API can be deployed on a server and serve multiple users.</li><li><strong>Separation:</strong> Model training and prediction can be managed independently.</li><li><strong>Accessibility:</strong> Applications can request predictions using HTTP requests.</li></ul><p>For example, an online shopping website can send customer information to a recommendation model through an API and receive product recommendations.</p><h3>3. Understanding the Architecture</h3><p>A basic ML inference API contains four important components:</p><ol><li><strong>Client:</strong> Sends input data to the API.</li><li><strong>FastAPI:</strong> Receives the request and validates the input.</li><li><strong>Machine Learning Model:</strong> Processes the input and generates a prediction.</li><li><strong>JSON Response:</strong> Sends the prediction back to the client.</li></ol><p>The process is simple:</p><p><strong>Client → FastAPI → ML Model → Prediction → Client</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlEYB_AicpR6YG_SWFhXkw.png" /><figcaption><em>How a client communicates with a machine learning model through an API.</em></figcaption></figure><p>There are two important stages in this process:</p><ul><li><strong>Training:</strong> The model learns patterns from the training dataset.</li><li><strong>Inference:</strong> The trained model uses new input data to generate predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDr71TZo4zppozlibZvcqA.png" /><figcaption><em>Training creates the model, while inference uses the saved model to make predictions.</em></figcaption></figure><p>The client does not need to know how the model was trained. It only needs to send the required input values.</p><h3>4. Technologies Used</h3><p>We will use the following technologies:</p><ul><li><strong>Python:</strong> Main programming language.</li><li><strong>Scikit-learn:</strong> Used to train the machine learning model.</li><li><strong>FastAPI:</strong> Used to create the API.</li><li><strong>Joblib:</strong> Used to save and load the trained model.</li><li><strong>Uvicorn:</strong> Runs the FastAPI application.</li></ul><p>We will use the Iris dataset because it is a beginner-friendly dataset commonly used for classification problems.</p><h3>5. Understanding the Iris Dataset</h3><p>The Iris dataset contains measurements of three flower species:</p><ul><li>Setosa</li><li>Versicolor</li><li>Virginica</li></ul><p>Each flower has four numerical features:</p><ol><li>Sepal length</li><li>Sepal width</li><li>Petal length</li><li>Petal width</li></ol><p>Our machine learning model will use these four measurements to predict the flower species.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMjKEgaEN71KBzIGw6X9WQ.png" /><figcaption><em>The Iris dataset uses four flower measurements to predict one of three species.</em></figcaption></figure><p>For example, when we provide the measurements of a flower, the model will analyze them and predict whether it belongs to Setosa, Versicolor, or Virginica.</p><h3>6. Project Implementation</h3><p>Now, let’s build the complete project step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLX82Wo4_01mOd_ebPZQhQ.png" /><figcaption><em>The project workflow separates model training from API-based prediction.</em></figcaption></figure><h3>Step 1: Create the Project Folder</h3><p>Create a folder named:</p><p>ml-inference-api</p><p>Inside this folder, create these files:</p><pre>ml-inference-api/<br>│<br>├── train_model.py<br>├── app.py<br>└── requirements.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX8-V_f3R46H5-WMdBENUg.png" /><figcaption><em>A simple folder structure keeps model training, API code, and dependencies organized.</em></figcaption></figure><p>The train_model.py file will train and save the model.</p><p>The app.py file will create the API and handle prediction requests.</p><p>The requirements.txt file will contain the required Python libraries.</p><h3>Step 2: Install the Required Libraries</h3><p>Open the project folder in VS Code and open the terminal.</p><p>Run:</p><pre>py -m pip install fastapi uvicorn scikit-learn joblib numpy</pre><p>These libraries provide everything needed to train the model and run the API.</p><h3>Step 3: Train the Machine Learning Model</h3><p>Open train_model.py and add the following code:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br>import joblib</pre><pre># Load the Iris dataset<br>iris = load_iris()</pre><pre>X = iris.data<br>y = iris.target</pre><pre># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre># Create the ML model<br>model = RandomForestClassifier(random_state=42)</pre><pre># Train the model<br>model.fit(X_train, y_train)</pre><pre># Test the model<br>predictions = model.predict(X_test)</pre><pre>accuracy = accuracy_score(y_test, predictions)</pre><pre>print(&quot;Model Training Completed&quot;)<br>print(&quot;Accuracy:&quot;, accuracy)</pre><pre># Save the trained model<br>joblib.dump(model, &quot;model.joblib&quot;)</pre><pre># Save the flower names<br>joblib.dump(iris.target_names, &quot;flower_names.joblib&quot;)</pre><pre>print(&quot;Model Saved Successfully&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>First, we load the Iris dataset from Scikit-learn.</li><li>We separate the input features and target labels.</li><li>We divide the dataset into training and testing data.</li><li>We create a Random Forest classification model.</li><li>The fit() function trains the model.</li><li>The predict() function generates predictions for the test data.</li><li>The accuracy score helps us evaluate the model.</li><li>Finally, Joblib saves the trained model and flower names.</li></ul><p>Run the training file:</p><pre>py train_model.py</pre><p>Example output:</p><pre>Model Training Completed<br>Accuracy: 1.0<br>Model Saved Successfully</pre><p>The exact accuracy can vary depending on the dataset split and model settings. The model files will be created automatically in the project folder.</p><h3>Step 4: Create the ML Inference API</h3><p>Now, open app.py and add the following code:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel, Field<br>import joblib</pre><pre># Create FastAPI application<br>app = FastAPI()</pre><pre># Load the saved model<br>model = joblib.load(&quot;model.joblib&quot;)</pre><pre># Load flower names<br>flower_names = joblib.load(&quot;flower_names.joblib&quot;)<br></pre><pre># Define input format<br>class FlowerInput(BaseModel):<br>    features: list[float] = Field(min_length=4, max_length=4)<br></pre><pre># Home route<br>@app.get(&quot;/&quot;)<br>def home():<br>    return {&quot;message&quot;: &quot;ML Inference API is Running&quot;}<br></pre><pre># Prediction route<br>@app.post(&quot;/predict&quot;)<br>def predict(data: FlowerInput):</pre><pre>    # Get input features<br>    input_data = [data.features]</pre><pre>    # Predict flower class<br>    prediction = model.predict(input_data)[0]</pre><pre>    # Get flower name<br>    flower = flower_names[prediction]</pre><pre>    # Return result<br>    return {<br>        &quot;prediction&quot;: int(prediction),<br>        &quot;species&quot;: str(flower)<br>    }</pre><p><strong>Explanation:</strong></p><ul><li>We import FastAPI to create the API.</li><li>We load the saved machine learning model using Joblib.</li><li>We load the flower names so that the prediction can be displayed clearly.</li><li>The FlowerInput class defines the expected request format.</li><li>The home route checks whether the API is running.</li><li>The /predict route receives flower measurements.</li><li>The model predicts the flower category.</li><li>Finally, the API returns the result in JSON format.</li></ul><p>The API validates that exactly four numerical measurements are provided.</p><h3>Step 5: Run the API</h3><p>Open the VS Code terminal and run:</p><pre>py -m uvicorn app:app --reload</pre><p>If everything works correctly, the terminal will show a message indicating that the server is running.</p><p>Open this address in your browser:</p><p><a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a></p><p>You should see:</p><pre>{<br>    &quot;message&quot;: &quot;ML Inference API is Running&quot;<br>}</pre><p>This confirms that our API is working.</p><h3>Step 6: Test the Prediction API</h3><p>FastAPI provides an automatic interactive documentation page.</p><p>Open:</p><p><a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a></p><p>Find the POST /predict endpoint.</p><p>Click <strong>Try it out</strong> and enter the following sample input:</p><pre>{<br>    &quot;features&quot;: [5.1, 3.5, 1.4, 0.2]<br>}</pre><p>Click <strong>Execute</strong>.</p><p>Example response:</p><pre>{<br>    &quot;prediction&quot;: 0,<br>    &quot;species&quot;: &quot;setosa&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjctGw4DGyp3ReoOhtBFSw.png" /><figcaption><em>A sample request sends flower measurements and receives a prediction in JSON format.</em></figcaption></figure><p>The model predicts that the flower belongs to the Setosa category.</p><p>We have now successfully created and tested a working ML inference API.</p><h3>7. Complete Workflow</h3><p>Let’s understand the complete process:</p><ol><li>Load the Iris dataset.</li><li>Train the Random Forest model.</li><li>Evaluate the model using test data.</li><li>Save the trained model using Joblib.</li><li>Start the FastAPI application.</li><li>Load the saved model into the API.</li><li>Send new flower measurements.</li><li>Receive the predicted flower species.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2t7kKDbxOWWgEAU4-Ps0Q.png" /><figcaption><em>The complete inference process converts input measurements into a predicted flower species.</em></figcaption></figure><p>This approach separates model development from model usage, making the application easier to maintain.</p><h3>8. Real-World Applications</h3><p>ML inference APIs are used in many industries.</p><p><strong>Healthcare:</strong> Applications can send medical test measurements to a trained model to support prediction tasks.</p><p><strong>E-commerce:</strong> Online shopping platforms can use recommendation models to suggest products.</p><p><strong>Banking:</strong> Financial applications can use trained models to identify potentially suspicious transactions.</p><p><strong>Education:</strong> Educational platforms can use prediction models to analyze student performance.</p><p><strong>Agriculture:</strong> Applications can send crop or leaf information to trained models to help identify possible plant diseases.</p><p>These examples show how trained machine learning models can become part of real software applications.</p><h3>9. Advantages and Limitations</h3><h3>Advantages</h3><ul><li>Easy integration with websites and applications.</li><li>The trained model can be reused.</li><li>Training and prediction can be maintained separately.</li><li>FastAPI provides automatic API documentation.</li><li>JSON makes it easy to exchange data between applications.</li></ul><h3>Limitations</h3><ul><li>The model may produce incorrect predictions.</li><li>The API requires a running server.</li><li>Large models may need more memory and processing power.</li><li>Multiple requests require appropriate server and deployment configuration.</li><li>Input validation and security are important when exposing an API publicly.</li></ul><p>An API does not automatically make a model accurate. The quality of predictions still depends on the training data, model, and evaluation process.</p><h3>10. Future Scope</h3><p>Machine learning inference APIs can be improved in several ways.</p><ul><li>Deploy the API using cloud platforms.</li><li>Add authentication to protect prediction endpoints.</li><li>Use Docker to package the application.</li><li>Add monitoring to track prediction performance.</li><li>Support larger datasets and more complex models.</li><li>Use optimized model formats to improve inference speed.</li></ul><p>These improvements can help transform a small academic project into a production-ready machine learning service.</p><h3>Conclusion</h3><p>Building a machine learning model is important, but making that model accessible to other applications is equally important.</p><p>In this article, we trained a Random Forest model using the Iris dataset, saved it using Joblib, and created a FastAPI application to provide predictions.</p><p>We also tested the API using FastAPI’s interactive documentation page.</p><p>This practical example demonstrates how Python and API technologies can work together to turn a trained machine learning model into a usable application.</p><p><strong>The main idea is simple: train the model once, save it, and use an API to request predictions whenever they are needed.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56f4015b5e44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Quantization: Making Machine Learning Models Smaller and Faster]]></title>
            <link>https://medium.com/@reddykowshik2008/model-quantization-making-machine-learning-models-smaller-and-faster-a290ce403bb6?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/a290ce403bb6</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 08:57:44 GMT</pubDate>
            <atom:updated>2026-12-04T08:57:44.118Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how quantization reduces model size and memory usage, explore different numerical precision formats, and build a practical Python project to compare a normal model with a quantized model.</em></p><h3>Introduction: Can We Make Machine Learning Models Smaller?</h3><p>Machine learning models can become large as they learn from more data and use more complex architectures.</p><p>A large model may require more memory and computing resources. This can make deployment difficult on laptops, mobile devices, and systems with limited hardware.</p><p>But what if we could reduce the size of a trained model without significantly affecting its predictions?</p><p>This is where <strong>model quantization</strong> becomes useful.</p><p>Model quantization is a technique that reduces the numerical precision used to represent a model’s weights and, in some methods, its activations. For example, a model may use 32-bit floating-point values before quantization and 8-bit integer values after quantization.</p><p>This can reduce memory requirements and may improve inference speed on compatible hardware.</p><p>In this article, we will understand model quantization, explore its advantages and limitations, and build a practical Python project using PyTorch to compare a normal model with a dynamically quantized model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*s5sqQEjV6FuvCvcJZHRgKw.png" /><figcaption><em>Model quantization reduces the numerical precision of machine learning models to help lower memory requirements and improve deployment efficiency.</em></figcaption></figure><h3>1. What Is Model Quantization?</h3><p>Model quantization is a model optimization technique that represents numerical values using lower precision.</p><p>A machine learning model contains weights and sometimes other numerical values that are used during prediction.</p><p>A traditional model may store many of these values using 32-bit floating-point precision, commonly called FP32.</p><p>Quantization can represent suitable values using lower precision formats, such as INT8.</p><p>For example:</p><ul><li>FP32 uses 32 bits per value.</li><li>FP16 uses 16 bits per value.</li><li>INT8 uses 8 bits per value.</li></ul><p>Using fewer bits can reduce the memory required to store model parameters.</p><p>However, quantization may introduce small numerical differences, so developers must evaluate prediction quality after applying it.</p><h3>2. Why Is Model Quantization Important?</h3><p>As machine learning applications become more common, developers need models that can run efficiently on different devices.</p><p>A large model may require significant memory and computing resources.</p><p>Quantization helps address some of these challenges.</p><p>Its main benefits include:</p><ul><li><strong>Reduced Model Size:</strong> Lower-precision values require fewer bits to store.</li><li><strong>Lower Memory Usage:</strong> Smaller model representations can reduce memory requirements.</li><li><strong>Potentially Faster Inference:</strong> Supported hardware can execute lower-precision operations efficiently.</li><li><strong>Efficient Deployment:</strong> Smaller models can be easier to deploy on resource-limited devices.</li><li><strong>Improved Hardware Utilization:</strong> Quantized operations may make better use of supported processors.</li></ul><p>Quantization does not guarantee faster inference in every situation. The improvement depends on the model, quantization method, hardware, and software framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*5z17PXiY5FQezMJBa4vgtw.png" /><figcaption><em>Quantization converts a model into a more compact numerical representation while aiming to preserve useful prediction behavior.</em></figcaption></figure><h3>3. Understanding Numerical Precision</h3><p>Numerical precision describes how accurately a computer represents a number.</p><p>Machine learning models perform many mathematical calculations, so the numerical format can affect their memory usage and performance.</p><p>Three commonly discussed formats are:</p><h3>A. FP32–32-bit Floating Point</h3><p>FP32 is commonly used during model training and inference.</p><p>It provides relatively high numerical precision but requires more memory than lower-precision formats.</p><h3>B. FP16–16-bit Floating Point</h3><p>FP16 uses half the number of bits compared with FP32.</p><p>It can reduce memory usage and accelerate supported operations on compatible hardware.</p><h3>C. INT8–8-bit Integer</h3><p>INT8 uses 8 bits to represent each value.</p><p>It can significantly reduce the storage required for model weights compared with FP32.</p><p>However, converting floating-point values into integers requires scaling and rounding, which can introduce numerical error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*wkWpEDVq2JKMzl8DVjeJ-Q.png" /><figcaption><em>A model contains numerical weights that can be represented using different precision formats depending on the selected quantization technique.</em></figcaption></figure><h3>4. How Does Quantization Work?</h3><p>Quantization maps values from a higher-precision numerical range into a lower-precision range.</p><p>For example, a floating-point value can be scaled and rounded to an integer representation.</p><p>A simplified quantization formula is:</p><p><strong>Quantized Value = Round(Original Value / Scale) + Zero Point</strong></p><p>Here:</p><ul><li><strong>Original Value:</strong> The original floating-point number.</li><li><strong>Scale:</strong> A factor used to map the original range to the quantized range</li><li><strong>Zero Point:</strong> An integer offset used to represent zero in the quantized range.</li><li><strong>Round:</strong> Converts the scaled value to an integer.</li></ul><p>The actual implementation also handles valid numerical ranges and clipping.</p><p>After quantization, the model uses the lower-precision representation for supported operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*MwIPj4XT8fCeR8ARE7rYHA.png" /><figcaption><em>Quantization maps floating-point values to lower-precision integer values using scaling, rounding, and an appropriate zero point.</em></figcaption></figure><h3>5. Types of Model Quantization</h3><p>There are different ways to apply quantization to a machine learning model.</p><h3>A. Post-Training Quantization</h3><p>Post-training quantization is applied after a model has already been trained.</p><p>Developers convert the trained model into a lower-precision representation.</p><p>It is useful when developers want to optimize an existing model without repeating the entire training process.</p><h3>B. Quantization-Aware Training</h3><p>Quantization-aware training simulates quantization effects during training.</p><p>The model learns while considering the numerical differences introduced by quantization.</p><p>This can help preserve model accuracy when lower-precision deployment is required.</p><h3>C. Dynamic Quantization</h3><p>In dynamic quantization, selected model weights are quantized ahead of inference, while activations are quantized dynamically during execution for supported operations.</p><p>It is commonly used for certain CPU-based models containing layers such as linear layers and recurrent layers.</p><p>Our practical project will demonstrate dynamic INT8 quantization of a small neural network using PyTorch.</p><h3>6. Understanding Model Size Reduction</h3><p>Model size depends partly on the number of parameters and the number of bits used to represent each parameter.</p><p>Consider a model containing 1 million parameters.</p><p>If each parameter uses 32 bits:</p><p>1,000,000 × 32 bits = 32,000,000 bits.</p><p>If each parameter uses 8 bits:</p><p>1,000,000 × 8 bits = 8,000,000 bits.</p><p>The theoretical weight-storage requirement becomes approximately one-fourth of the original.</p><p>This is a simplified calculation. Actual saved model files may contain additional information, metadata, and quantization parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*-68Th2papNSJhYKxYHuSoQ.png" /><figcaption><em>Lower-precision model weights can reduce storage requirements, although actual model file sizes depend on additional model information and quantization metadata.</em></figcaption></figure><p>7. Practical Implementation: Comparing Normal and Quantized Models Using Python</p><p>Now let’s build a small project using PyTorch.</p><p>We will:</p><ol><li>Create a neural network.</li><li>Generate sample input data.</li><li>Measure the original model size.</li><li>Apply dynamic INT8 quantization.</li><li>Measure the quantized model size.</li><li>Compare prediction outputs.</li><li>Measure inference latency.</li></ol><p><strong>Important:</strong> This demonstration uses CPU dynamic quantization of supported linear layers. It does not require a dedicated GPU.</p><h3>Step 1 — Install Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install torch numpy</pre><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named Model_Quantization_Project.</p><pre>Model_Quantization_Project/<br>│<br>├── quantization.py<br>└── requirements.txt</pre><h3>Step 3 — Create requirements.txt</h3><p>Add:</p><pre>torch<br>numpy</pre><h3>Step 4 — Create the Python Program</h3><p>Create a file named quantization.py.</p><pre>import copy<br>import io<br>import time</pre><pre>import torch<br>import torch.nn as nn<br></pre><pre># Create a simple neural network<br>class SimpleModel(nn.Module):</pre><pre>    def __init__(self):</pre><pre>        super().__init__()</pre><pre>        self.network = nn.Sequential(<br>            nn.Linear(100, 256),<br>            nn.ReLU(),<br>            nn.Linear(256, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 10)<br>        )</pre><pre>    def forward(self, x):</pre><pre>        return self.network(x)<br></pre><pre># Create original model<br>model = SimpleModel()<br>model.eval()</pre><pre># Generate sample input<br>input_data = torch.randn(256, 100)</pre><pre># Apply dynamic INT8 quantization<br>quantized_model = torch.ao.quantization.quantize_dynamic(<br>    copy.deepcopy(model),<br>    {nn.Linear},<br>    dtype=torch.qint8<br>)</pre><pre>quantized_model.eval()<br></pre><pre># Function to calculate model size<br>def get_model_size(model):</pre><pre>    buffer = io.BytesIO()</pre><pre>    torch.save(model.state_dict(), buffer)</pre><pre>    return len(buffer.getvalue()) / 1024<br></pre><pre># Function to measure inference time<br>def measure_time(model, data):</pre><pre>    # Warm-up<br>    with torch.no_grad():</pre><pre>        for _ in range(10):<br>            model(data)</pre><pre>    # Start timer<br>    start = time.perf_counter()</pre><pre>    with torch.no_grad():</pre><pre>        for _ in range(100):<br>            model(data)</pre><pre>    end = time.perf_counter()</pre><pre>    return (end - start) / 100 * 1000<br></pre><pre># Compare model sizes<br>original_size = get_model_size(model)</pre><pre>quantized_size = get_model_size(quantized_model)<br></pre><pre># Compare predictions<br>with torch.no_grad():</pre><pre>    original_output = model(input_data)</pre><pre>    quantized_output = quantized_model(input_data)</pre><pre>    difference = torch.mean(<br>        torch.abs(original_output - quantized_output)<br>    ).item()<br></pre><pre># Measure inference time<br>original_time = measure_time(model, input_data)</pre><pre>quantized_time = measure_time(<br>    quantized_model,<br>    input_data<br>)<br></pre><pre># Calculate size reduction<br>size_reduction = (<br>    (original_size - quantized_size)<br>    / original_size<br>) * 100<br></pre><pre># Display results<br>print(&quot;MODEL QUANTIZATION RESULTS&quot;)</pre><pre>print(&quot;\nOriginal Model Size:&quot;,<br>      round(original_size, 2), &quot;KB&quot;)</pre><pre>print(&quot;Quantized Model Size:&quot;,<br>      round(quantized_size, 2), &quot;KB&quot;)</pre><pre>print(&quot;Size Reduction:&quot;,<br>      round(size_reduction, 2), &quot;%&quot;)</pre><pre>print(&quot;\nOriginal Model Latency:&quot;,<br>      round(original_time, 3), &quot;ms&quot;)</pre><pre>print(&quot;Quantized Model Latency:&quot;,<br>      round(quantized_time, 3), &quot;ms&quot;)</pre><pre>print(&quot;\nMean Absolute Output Difference:&quot;,<br>      round(difference, 6))<br></pre><pre># Save quantized model<br>torch.save(<br>    quantized_model.state_dict(),<br>    &quot;quantized_model.pth&quot;<br>)</pre><pre>print(&quot;\nQuantized model saved successfully!&quot;)</pre><h3>Step 5 — Run the Program</h3><p>Open the terminal inside your project folder and execute:</p><pre>py quantization.py</pre><p>The program creates an original model and a dynamically quantized model.</p><p>It then compares their serialized state-dictionary sizes, inference latency, and output differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*wCDU57SqN2Cv2aEkIULwZA.png" /><figcaption><em>The quantization workflow starts with a trained model, applies lower-precision representation, and evaluates the resulting model.</em></figcaption></figure><h3>Step 6 — Understand the Output</h3><p>The output will display the comparison between the original and quantized models.</p><p>Example output format:</p><pre>MODEL QUANTIZATION RESULTS</pre><pre>Original Model Size: 250.00 KB<br>Quantized Model Size: 75.00 KB<br>Size Reduction: 70.00 %</pre><pre>Original Model Latency: 5.20 ms<br>Quantized Model Latency: 3.80 ms</pre><pre>Mean Absolute Output Difference: 0.002145</pre><pre>Quantized model saved successfully!</pre><p><strong>These values are illustrative only.</strong> Your actual results will depend on your PyTorch version, computer, model, and system load.</p><p>The mean absolute output difference indicates how much the predictions changed on average for the sample inputs.</p><p>A smaller difference indicates closer numerical outputs, but it does not by itself prove that classification accuracy is unchanged.</p><p>Also, the measured size is the serialized state dictionary, not a complete production deployment package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*iudExi7QRvNC9hNfXsGU4A.png" /><figcaption><em>A Python implementation uses PyTorch to create, quantize, and benchmark a neural network.</em></figcaption></figure><h3>8. Understanding the Results</h3><p>Our project compares three important measurements.</p><h3>A. Model Size</h3><p>The original model uses higher-precision weights, while the quantized model uses INT8 weights for supported linear layers.</p><p>A smaller serialized model can reduce storage requirements.</p><h3>B. Inference Latency</h3><p>Latency measures the time required to process the input batch.</p><p>A lower latency indicates faster execution for that specific test.</p><p>However, quantization does not guarantee a speed improvement for every model or device.</p><h3>C. Output Difference</h3><p>Quantization can introduce small numerical differences.</p><p>Developers should evaluate the model using a suitable validation dataset and compare task-specific metrics such as accuracy, precision, recall, or F1-score.</p><p>The best quantization method is one that provides useful efficiency improvements while maintaining acceptable model quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*-3yCH7ZI35PMRX0Icxyd3g.png" /><figcaption><em>A performance dashboard helps compare original and quantized models using model size, inference latency, and prediction differences.</em></figcaption></figure><h3>9. Advantages of Model Quantization</h3><ul><li><strong>Smaller Models:</strong> Reduces the number of bits used for supported model parameters.</li><li><strong>Lower Memory Requirements:</strong> Helps models fit into limited memory.</li><li><strong>Efficient Deployment:</strong> Makes some models easier to deploy on resource-constrained devices.</li><li><strong>Potential Speed Improvements:</strong> Can accelerate supported operations on compatible hardware.</li><li><strong>Reduced Storage:</strong> Smaller model representations require less storage space.</li></ul><h3>10. Challenges and Limitations</h3><p>Quantization also has some limitations.</p><ul><li><strong>Accuracy Changes:</strong> Lower numerical precision can affect prediction quality.</li><li><strong>Hardware Dependency:</strong> Performance improvements depend on hardware support.</li><li><strong>Framework Compatibility:</strong> Not every model operation supports every quantization method.</li><li><strong>Additional Testing:</strong> Developers must validate model quality after quantization.</li><li><strong>Implementation Complexity:</strong> Selecting suitable precision and quantization methods requires experimentation.</li></ul><p>Quantization should always be evaluated using the actual application workload.</p><h3>11. Future Scope</h3><p>Model quantization continues to develop as machine learning moves toward mobile devices, edge computing, and efficient AI deployment.</p><p>Some important directions include:</p><ul><li><strong>INT4 Quantization:</strong> Using even fewer bits for suitable model weights.</li><li><strong>Mixed Precision:</strong> Combining different numerical formats within one model.</li><li><strong>Edge AI:</strong> Running compact models on mobile and embedded devices.</li><li><strong>Quantization-Aware Training:</strong> Improving model behavior under low-precision constraints.</li><li><strong>Hardware Acceleration:</strong> Using specialized hardware for efficient quantized operations.</li><li><strong>Model Optimization:</strong> Combining quantization with pruning and other optimization techniques.</li></ul><p>These techniques can help developers build more efficient machine learning applications.</p><h3>Conclusion: Smaller Models Can Make AI More Efficient</h3><p>Model quantization is an important optimization technique that reduces the numerical precision used to represent machine learning models.</p><p>By using lower-precision formats such as INT8, developers can reduce model storage and memory requirements and may improve inference performance on compatible hardware.</p><p>In our practical project, we used PyTorch to create a neural network, apply dynamic quantization, and compare model size, inference latency, and prediction differences.</p><p>The most important lesson is that <strong>model optimization is not only about making a model smaller; it is about finding the right balance between efficiency and prediction quality.</strong></p><p>Understanding quantization helps developers prepare machine learning models for efficient deployment across different computing environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a290ce403bb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring Machine Learning Model Latency and Throughput: Build Your Own Benchmarking Application]]></title>
            <link>https://medium.com/@reddykowshik2008/measuring-machine-learning-model-latency-and-throughput-build-your-own-benchmarking-application-31598d0e72e3?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/31598d0e72e3</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 08:47:56 GMT</pubDate>
            <atom:updated>2026-12-04T08:47:56.635Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding prediction speed, concurrent requests, performance testing, and how to measure the efficiency of a machine learning API using Python.</em></p><h3>Introduction: Is an Accurate Model Always a Fast Model?</h3><p>Imagine an online shopping application that uses machine learning to recommend products to customers.</p><p>A customer opens the application and requests recommendations. The machine learning model generates accurate predictions, but it takes several seconds to return the results.</p><p>Now imagine thousands of customers accessing the application at the same time. Will the system respond quickly to everyone?</p><p>This introduces an important challenge in machine learning deployment: <strong>model performance</strong>.</p><p>A machine learning model should not only generate accurate predictions. It should also respond within an acceptable time and handle the required number of requests.</p><p>Two important measurements help developers understand this performance:</p><ul><li><strong>Latency:</strong> How long a request takes to receive a response.</li><li><strong>Throughput:</strong> How many requests a system can process within a given period.</li></ul><p>In this article, we will understand these measurements and build a practical Python benchmarking application to test a machine learning prediction API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*08pIA3jYsLCDcYsQ49BrJw.png" /></figure><h3>1. What Is Machine Learning Model Latency?</h3><p>Latency is the time taken by a system to process a request and return a response.</p><p>In machine learning applications, latency measures how long a prediction request takes.</p><p>For example, when a user submits information to a prediction API, the application receives the input, processes it using a trained model, and returns the prediction.</p><p>If the complete request takes 200 milliseconds, the measured request latency is 200 milliseconds.</p><p>Lower latency is generally important for applications that require quick responses.</p><p><strong>Examples:</strong></p><ul><li>Face recognition systems.</li><li>Online product recommendations.</li><li>Fraud detection during payments.</li><li>Voice assistants.</li><li>Real-time image classification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*mZ7G8FIDFDirm3iEyBZSOA.png" /></figure><h3>2. What Is Throughput?</h3><p>Throughput measures how many requests a system can successfully process during a specific period.</p><p>It is commonly expressed as requests per second (RPS).</p><p>For example:</p><p>Imagine an API processes 100 prediction requests in 10 seconds.</p><p>Its average throughput is:</p><p>Throughput = Total Requests / Total Time</p><p>Throughput = 100 / 10</p><p>Throughput = 10 requests per second.</p><p>Higher throughput means the system can handle more requests within the same period, although the actual requirement depends on the application.</p><p>A system may have low latency for one user but struggle when many users send requests simultaneously.</p><p>That is why developers measure both latency and throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*JyJhE-9WBc70ckGAb1wU7g.png" /></figure><h3>3. Important Performance Measurements</h3><p>Developers use different measurements to understand the performance of machine learning applications.</p><h3>A. Average Latency</h3><p>Average latency is the average time taken by all measured requests.</p><p>Formula:</p><p>Average Latency = Sum of Request Latencies / Total Requests</p><p>It provides an overall view of response time.</p><p>However, averages can hide slow individual requests.</p><h3>B. P95 Latency</h3><p>P95 latency, or the 95th percentile latency, represents the response-time threshold within which approximately 95% of measured requests completed.</p><p>For example, if P95 latency is 300 milliseconds, approximately 95% of the measured requests completed within 300 milliseconds.</p><p>This measurement helps developers understand slower requests that an average might hide.</p><h3>C. Throughput</h3><p>Throughput measures the number of completed requests per second.</p><p>Formula:</p><p>Throughput = Successful Requests / Total Test Duration</p><h3>D. Maximum Latency</h3><p>Maximum latency is the longest response time observed during the test.</p><p>It helps identify unusually slow requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*c5T4IJWERsWu8LZn0E651g.png" /></figure><h3>4. Understanding Performance Benchmarking</h3><p>Benchmarking is the process of testing a system under controlled conditions to measure its performance.</p><p>In machine learning, benchmarking helps developers understand how quickly a model generates predictions and how well its API handles multiple requests.</p><p>A simple benchmarking process includes:</p><ol><li>Prepare a trained machine learning model.</li><li>Deploy the model through an API.</li><li>Send multiple prediction requests.</li><li>Measure the response time of each request.</li><li>Calculate average and P95 latency.</li><li>Calculate throughput.</li><li>Compare the results under different testing conditions.</li></ol><p>Benchmarking can also reveal performance problems such as server overload, slow preprocessing, and limited computing resources.</p><h3>5. Understanding the Benchmarking Architecture</h3><p>Our practical application contains four main components:</p><p><strong>1. Machine Learning Model:</strong> The trained model generates predictions.</p><p><strong>2. FastAPI Server:</strong> Provides an endpoint that accepts prediction requests.</p><p><strong>3. Benchmarking Script:</strong> Sends multiple requests to the API.</p><p><strong>4. Performance Measurement:</strong> Calculates latency, P95 latency, maximum latency, and throughput.</p><p>The benchmarking script sends requests to the API and records how long each request takes.</p><p>The collected measurements are then used to understand the performance of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*4CG6UrcpcBA8gowLw0XA_w.png" /></figure><h3>6. Technologies Used in Our Practical Project</h3><p>We will use the following technologies:</p><ul><li><strong>Python:</strong> Main programming language.</li><li><strong>Scikit-learn:</strong> Training the machine learning model.</li><li><strong>FastAPI:</strong> Creating the prediction API.</li><li><strong>Uvicorn:</strong> Running the API server.</li><li><strong>Pandas:</strong> Organizing performance results.</li><li><strong>Requests:</strong> Sending HTTP requests.</li><li><strong>NumPy:</strong> Calculating statistical measurements.</li><li><strong>Matplotlib:</strong> Visualizing benchmarking results.</li></ul><p>For this demonstration, we will use the Iris dataset from Scikit-learn to build a flower classification model.</p><h3>7. Practical Implementation: Building a Benchmarking Application</h3><h3>Step 1 — Install the Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install pandas numpy matplotlib scikit-learn fastapi uvicorn requests</pre><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named ML_Performance_Benchmark.</p><pre>ML_Performance_Benchmark/<br>│<br>├── train_model.py<br>├── app.py<br>├── benchmark.py<br>└── requirements.txt</pre><h3>Step 3 — Train and Save the Machine Learning Model</h3><p>Create a file named train_model.py.</p><pre>import joblib</pre><pre>from sklearn.datasets import load_iris<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split</pre><pre># Load dataset<br>iris = load_iris()</pre><pre>X = iris.data<br>y = iris.target</pre><pre># Split dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre># Create model<br>model = RandomForestClassifier(<br>    n_estimators=100,<br>    random_state=42<br>)</pre><pre># Train model<br>model.fit(X_train, y_train)</pre><pre># Save model and class names<br>joblib.dump(<br>    {<br>        &quot;model&quot;: model,<br>        &quot;target_names&quot;: iris.target_names.tolist()<br>    },<br>    &quot;iris_model.pkl&quot;<br>)</pre><pre>print(&quot;Model trained successfully!&quot;)<br>print(&quot;Model accuracy:&quot;, model.score(X_test, y_test))<br>print(&quot;Model saved successfully!&quot;)</pre><p>Run the program:</p><pre>py train_model.py</pre><p>The model will be trained using the Iris dataset and saved as iris_model.pkl.</p><h3>Step 4 — Create the Machine Learning Prediction API</h3><p>Create a file named app.py.</p><pre>import joblib</pre><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>app = FastAPI(title=&quot;ML Performance Benchmark API&quot;)</pre><pre># Load trained model<br>saved_data = joblib.load(&quot;iris_model.pkl&quot;)</pre><pre>model = saved_data[&quot;model&quot;]<br>target_names = saved_data[&quot;target_names&quot;]<br></pre><pre>class FlowerInput(BaseModel):<br>    features: list[float]<br></pre><pre>@app.post(&quot;/predict&quot;)<br>def predict(data: FlowerInput):</pre><pre>    if len(data.features) != 4:<br>        return {<br>            &quot;error&quot;: &quot;Please provide exactly 4 measurements.&quot;<br>        }</pre><pre>    prediction = model.predict([data.features])[0]</pre><pre>    return {<br>        &quot;prediction&quot;: target_names[int(prediction)]<br>    }<br></pre><pre>@app.get(&quot;/&quot;)<br>def home():</pre><pre>    return {<br>        &quot;message&quot;: &quot;ML Benchmark API is running&quot;<br>    }</pre><p>This API accepts flower measurements and returns the predicted flower species.</p><h3>Step 5 — Run the API Server</h3><p>Open the terminal and execute:</p><pre>py -m uvicorn app:app --reload</pre><p>Open this address in your browser:</p><p><a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a></p><p>FastAPI provides an interactive interface for testing the prediction endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*WJqRMEibPqUXgMMNRB6HKw.png" /></figure><h3>Step 6 — Create the Benchmarking Script</h3><p>Create a file named benchmark.py.</p><p>This program will send multiple requests to the prediction API and measure their response times.</p><pre>import time<br>import requests<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>from concurrent.futures import ThreadPoolExecutor</pre><pre># API endpoint<br>URL = &quot;http://127.0.0.1:8000/predict&quot;</pre><pre># Sample input<br>data = {<br>    &quot;features&quot;: [5.1, 3.5, 1.4, 0.2]<br>}</pre><pre># Number of requests<br>TOTAL_REQUESTS = 100</pre><pre># Number of concurrent workers<br>WORKERS = 10</pre><pre># Store response times<br>latencies = []<br></pre><pre># Function to send one request<br>def send_request():</pre><pre>    start = time.perf_counter()</pre><pre>    response = requests.post(<br>        URL,<br>        json=data,<br>        timeout=30<br>    )</pre><pre>    elapsed = time.perf_counter() - start</pre><pre>    response.raise_for_status()</pre><pre>    return elapsed<br></pre><pre># Start benchmarking<br>start_time = time.perf_counter()</pre><pre>with ThreadPoolExecutor(max_workers=WORKERS) as executor:</pre><pre>    results = list(<br>        executor.map(<br>            lambda _: send_request(),<br>            range(TOTAL_REQUESTS)<br>        )<br>    )</pre><pre>total_time = time.perf_counter() - start_time</pre><pre>latencies = results</pre><pre># Calculate performance measurements<br>average_latency = np.mean(latencies)</pre><pre>p95_latency = np.percentile(<br>    latencies, 95<br>)</pre><pre>maximum_latency = np.max(latencies)</pre><pre>throughput = TOTAL_REQUESTS / total_time</pre><pre># Display results<br>print(&quot;MACHINE LEARNING PERFORMANCE RESULTS&quot;)</pre><pre>print(&quot;Total Requests:&quot;, TOTAL_REQUESTS)</pre><pre>print(&quot;Successful Requests:&quot;, len(latencies))</pre><pre>print(&quot;Average Latency:&quot;,<br>      round(average_latency * 1000, 2), &quot;ms&quot;)</pre><pre>print(&quot;P95 Latency:&quot;,<br>      round(p95_latency * 1000, 2), &quot;ms&quot;)</pre><pre>print(&quot;Maximum Latency:&quot;,<br>      round(maximum_latency * 1000, 2), &quot;ms&quot;)</pre><pre>print(&quot;Total Test Time:&quot;,<br>      round(total_time, 2), &quot;seconds&quot;)</pre><pre>print(&quot;Throughput:&quot;,<br>      round(throughput, 2), &quot;requests/second&quot;)<br></pre><pre># Save results<br>df = pd.DataFrame({<br>    &quot;Request&quot;: range(1, TOTAL_REQUESTS + 1),<br>    &quot;Latency_ms&quot;: np.array(latencies) * 1000<br>})</pre><pre>df.to_csv(&quot;benchmark_results.csv&quot;, index=False)</pre><pre># Create latency graph<br>plt.plot(df[&quot;Request&quot;], df[&quot;Latency_ms&quot;])</pre><pre>plt.title(&quot;Machine Learning API Latency&quot;)<br>plt.xlabel(&quot;Request Number&quot;)<br>plt.ylabel(&quot;Latency (milliseconds)&quot;)</pre><pre>plt.grid(True)<br>plt.savefig(&quot;latency_graph.png&quot;)<br>plt.show()</pre><pre>print(&quot;Benchmark results saved successfully!&quot;)</pre><h3>Step 7 — Run the Benchmarking Program</h3><p>Keep the FastAPI server running in the first terminal.</p><p>Open a second terminal in the same project folder.</p><p>Execute:</p><pre>py benchmark.py</pre><p>The program sends 100 requests using 10 concurrent workers.</p><p>It calculates:</p><ul><li>Average latency.</li><li>P95 latency.</li><li>Maximum latency.</li><li>Total test duration.</li><li>Throughput.</li></ul><p>The program also creates two output files:</p><ul><li>benchmark_results.csv</li><li>latency_graph.png</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*G2u0Wo_vTR1qGm10Xo3sRg.png" /></figure><h3>Step 8 — Understand the Output</h3><p>Your actual values will depend on your computer, server configuration, and current system load.</p><p>Example output format:</p><pre>MACHINE LEARNING PERFORMANCE RESULTS</pre><pre>Total Requests: 100<br>Successful Requests: 100</pre><pre>Average Latency: 12.50 ms<br>P95 Latency: 18.20 ms<br>Maximum Latency: 25.40 ms</pre><pre>Total Test Time: 0.45 seconds<br>Throughput: 222.22 requests/second</pre><pre>Benchmark results saved successfully!</pre><p>These numbers are illustrative only. Your results will be different.</p><p>The benchmarking script measures HTTP request-response time, which includes network and API overhead as well as model processing. It is not a measurement of pure model computation time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*8ezVevuubUohZduBp0I0rw.png" /></figure><h3>8. Understanding the Benchmarking Results</h3><p>The benchmarking results help us understand how the prediction API behaves.</p><p><strong>Average Latency:</strong> Shows the average time required to complete a request.</p><p><strong>P95 Latency:</strong> Shows the response-time threshold for approximately 95% of requests.</p><p><strong>Maximum Latency:</strong> Identifies the slowest request in the test.</p><p><strong>Throughput:</strong> Shows how many requests were completed per second during the test.</p><p>If latency increases significantly under heavier request loads, the system may need optimization or additional computing resources.</p><p>A single test is not enough to make a production decision. Developers should repeat tests under different conditions and compare the results.</p><h3>9. Advantages of Performance Benchmarking</h3><ul><li><strong>Identifies Slow Components:</strong> Helps developers discover performance bottlenecks.</li><li><strong>Improves User Experience:</strong> Helps applications meet response-time requirements.</li><li><strong>Supports Capacity Planning:</strong> Helps estimate how many requests a system can handle.</li><li><strong>Enables Comparisons:</strong> Allows developers to compare different models and deployment configurations.</li><li><strong>Supports Optimization:</strong> Helps evaluate whether a change improves performance.</li></ul><h3>10. Challenges and Limitations</h3><p>Benchmarking also has some limitations.</p><ul><li>Results can vary depending on CPU, memory, and background processes.</li><li>Network and API overhead can affect measured latency.</li><li>Testing on a local machine does not represent every production environment.</li><li>More concurrent requests can increase server load.</li><li>A small test dataset may not represent real-world usage.</li></ul><p>For reliable benchmarking, developers should use repeated tests, realistic workloads, and consistent testing conditions.</p><h3>11. Future Scope</h3><p>Performance benchmarking can be improved using more advanced tools and techniques.</p><ul><li><strong>Load Testing:</strong> Tools such as Locust can simulate many users.</li><li><strong>GPU Benchmarking:</strong> Compare inference performance using CPU and GPU hardware.</li><li><strong>Model Optimization:</strong> Compare different model sizes and optimization techniques.</li><li><strong>Cloud Deployment:</strong> Test model APIs under real deployment conditions.</li><li><strong>Automated Monitoring:</strong> Track latency and throughput continuously.</li><li><strong>Distributed Testing:</strong> Generate requests from multiple machines to simulate larger workloads.</li></ul><p>These improvements can help developers understand the performance of machine learning systems at a larger scale.</p><h3>Conclusion: Accuracy Is Only One Part of Machine Learning Performance</h3><p>A machine learning model should not only produce accurate predictions. It should also respond efficiently and handle the number of requests expected by the application.</p><p>Latency helps developers understand response speed, while throughput measures how many requests a system can process within a given period.</p><p>In our practical project, we trained a Random Forest model using Scikit-learn, deployed it through FastAPI, and created a Python benchmarking script to measure its performance.</p><p>The main lesson is that <strong>measuring machine learning performance is essential before deploying a model into a real-world application.</strong></p><p>By understanding latency, throughput, and benchmarking, developers can build machine learning systems that are faster, more efficient, and better prepared for real-world workloads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31598d0e72e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing MCP Integrations: Authentication, Permissions, and Safe Tool Access]]></title>
            <link>https://medium.com/@reddykowshik2008/securing-mcp-integrations-authentication-permissions-and-safe-tool-access-6b31156b7289?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b31156b7289</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 08:46:07 GMT</pubDate>
            <atom:updated>2026-12-04T08:46:07.502Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding how to protect AI applications when they connect to external tools, APIs, databases, and services.</em></p><h3>Introduction: What If an AI Assistant Gets Access to the Wrong Tool?</h3><p>Imagine an AI assistant connected to a company’s email, database, and file system.</p><p>A user asks the assistant to summarize a document. Instead of only reading the requested document, the assistant accidentally accesses confidential files or attempts an unauthorized operation.</p><p>Why could this happen?</p><p>AI applications are increasingly connected to external tools and services. These connections make applications more powerful, but they also introduce security risks.</p><p>The Model Context Protocol (MCP) provides a standardized way for AI applications to connect with external tools and data sources.</p><p>However, connecting an AI application to a tool does not automatically make that connection secure.</p><p>Developers must carefully manage authentication, permissions, input validation, and tool execution.</p><p>In this article, we will understand MCP security challenges and build a beginner-friendly Python demonstration that checks user identity, controls permissions, validates inputs, and protects tool operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*LkJ9fIEqhsE3PFQmAgy8hA.png" /><figcaption><em>Secure MCP integrations help AI applications connect with external tools while protecting sensitive information and controlling access.</em></figcaption></figure><h3>1. Understanding MCP</h3><p>Model Context Protocol (MCP) is an open protocol that helps AI applications communicate with external tools, resources, and services.</p><p>For example, an AI assistant may need to:</p><ul><li>Read information from a database.</li><li>Access files and documents.</li><li>Search information through an external API.</li><li>Retrieve project details.</li><li>Perform approved actions using connected tools.</li></ul><p>MCP provides a standardized communication structure for these interactions.</p><p>A basic MCP environment contains three important components:</p><p><strong>1. MCP Host:</strong> The AI application that manages the interaction.</p><p><strong>2. MCP Client:</strong> The component that communicates with an MCP server.</p><p><strong>3. MCP Server:</strong> The component that exposes tools, resources, and prompts.</p><p>The server makes selected capabilities available to the AI application.</p><p>However, every connected tool must have appropriate security controls.</p><h3>2. Understanding MCP Architecture</h3><p>Consider an AI assistant connected to a company database.</p><p>The assistant sends a request through an MCP client. The client communicates with the MCP server, which provides access to approved tools or resources.</p><p>A simplified workflow is:</p><ol><li>The user sends a request to the AI application.</li><li>The AI application identifies an appropriate tool.</li><li>The MCP client communicates with the MCP server.</li><li>The server checks the request and applies its security rules.</li><li>The approved tool performs the operation.</li><li>The result is returned to the AI application.</li></ol><p>Security controls should be applied at the server and underlying resource, not only in the AI assistant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*0DrTu2KGUP6RcihMvV9RTQ.png" /><figcaption><em>Basic MCP architecture showing how an AI client communicates with an MCP server to access approved tools and data sources.</em></figcaption></figure><h3>3. Why Is MCP Security Important?</h3><p>MCP integrations can provide access to important business resources.</p><p>If security is not properly implemented, attackers or unintended tool calls may cause problems.</p><p>Some important security risks include:</p><h3>A. Unauthorized Access</h3><p>A user may attempt to access a tool or resource without having the required permission.</p><p>For example, a normal employee should not automatically receive administrator access to a company’s database.</p><h3>B. Prompt Injection</h3><p>Malicious instructions may appear inside a webpage, document, email, or tool response.</p><p>An AI model might incorrectly treat those instructions as commands and attempt an unsafe tool operation.</p><h3>C. Sensitive Data Exposure</h3><p>A tool may accidentally return confidential information to a user who is not authorized to access it.</p><h3>D. Unsafe Tool Execution</h3><p>A tool that executes commands, modifies files, or updates databases can cause serious problems if its inputs and permissions are not properly controlled.</p><h3>E. Token and Credential Theft</h3><p>If authentication tokens or API keys are exposed, attackers may use them to access protected services.</p><p>OWASP identifies these and other risks as important areas when securing MCP deployments. &lt;Cite refs={[“turn942322search0”,”turn942322search5&quot;]}/&gt;</p><h3>4. Authentication: Verifying User Identity</h3><p>Authentication is the process of verifying who is making a request.</p><p>Before allowing access to a protected tool, an application should verify the user’s identity.</p><p>Common authentication methods include:</p><ul><li>API keys.</li><li>OAuth 2.1 access tokens.</li><li>Identity verification.</li><li>Secure session management.</li></ul><p>For remote MCP services, the MCP authorization specification describes OAuth-based security requirements.</p><p>Access tokens should be intended for the specific server receiving them. They should not be blindly forwarded to other services. &lt;Cite refs={[“turn942322search1”]}/&gt;</p><p>For example, imagine a company application with three users:</p><ul><li>Admin</li><li>Developer</li><li>Normal user</li></ul><p>The application should verify the user’s credentials before allowing access to protected operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*anp2DNyV2rWyLF4SbGv9Qg.png" /><figcaption><em>Authentication verifies a user’s identity before allowing access to protected MCP services and connected tools.</em></figcaption></figure><h3>5. Authorization: Controlling Permissions</h3><p>Authentication answers:</p><p><strong>Who are you?</strong></p><p>Authorization answers:</p><p><strong>What are you allowed to do?</strong></p><p>After verifying identity, an application must check the permissions associated with that user.</p><p>For example:</p><p>User RoleRead ReportUpdate ReportAdminYesYesDeveloperYesNoUserYesNo</p><p>This is an example of Role-Based Access Control (RBAC).</p><p>Each role receives only the permissions required for its responsibilities.</p><p>A useful security principle is <strong>Least Privilege</strong>.</p><p>It means giving users and tools only the minimum permissions necessary to perform their tasks.</p><p>For example, if an AI assistant only needs to read customer information, it should not receive permission to delete customer records.</p><p>OWASP recommends scoped credentials and least-privilege access for MCP integrations. &lt;Cite refs={[“turn942322search0”,”turn942322search3&quot;]}/&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*wr4RI-UkJ02izIf7E_2LXQ.png" /><figcaption><em>Role-based authorization restricts tool access according to user permissions and prevents unnecessary privileges.</em></figcaption></figure><h3>6. Important Security Practices for MCP</h3><p>Developers should apply several security practices when connecting AI applications to external tools.</p><h3>A. Input Validation</h3><p>Every tool should validate the data it receives.</p><p>For example, a tool that searches reports should reject empty or excessively long search queries.</p><h3>B. Least Privilege</h3><p>Give each tool only the permissions it needs.</p><p>A read-only tool should not be able to modify or delete data.</p><h3>C. Secure Credential Storage</h3><p>API keys and access tokens should not be exposed in source code or public repositories.</p><p>Use environment variables or a secure credential store.</p><h3>D. Human Approval</h3><p>Sensitive actions such as deleting records, sending emails, or transferring money should require explicit user confirmation.</p><h3>E. Sandboxing</h3><p>Tools that execute code or commands should run in restricted environments with limited access to files and networks.</p><h3>F. Monitoring</h3><p>Record tool activity, authentication failures, permission denials, and suspicious requests.</p><p>These controls help reduce the impact of unsafe or unauthorized tool calls. &lt;Cite refs={[“turn942322search0”,”turn942322search12&quot;,”turn942322search16&quot;]}/&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*akqoEaBsk3Y521OjMQQlhg.png" /><figcaption><em>Secure tool execution combines input validation, least privilege, data protection, and monitoring.</em></figcaption></figure><h3>7. Common MCP Security Threats</h3><p>Understanding common threats helps developers design safer integrations.</p><p><strong>Prompt Injection:</strong> Malicious instructions attempt to influence an AI application into performing unintended actions.</p><p><strong>Tool Poisoning:</strong> A tool’s description or metadata may contain misleading instructions that influence an AI system.</p><p><strong>Data Leakage:</strong> Sensitive information may be exposed through tool responses, logs, or unauthorized access.</p><p><strong>Excessive Permissions:</strong> A tool may receive more access than it needs.</p><p><strong>Credential Exposure:</strong> API keys or tokens may be leaked through configuration files or logs.</p><p><strong>Unsafe Tool Parameters:</strong> Poorly validated parameters may cause unintended operations.</p><p>A secure MCP implementation should treat tool descriptions, inputs, and outputs as data that requires validation rather than automatically trusting them. &lt;Cite refs={[“turn942322search3”,”turn942322search5&quot;]}/&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*jLL_V5Ln3Z9sycIEsS_0WQ.png" /><figcaption><em>Common MCP security threats include prompt injection, malicious tools, unauthorized access, and sensitive data leakage.</em></figcaption></figure><h3>8. Practical Implementation: Building a Secure Tool Access Demo</h3><p>Now let’s create a small Python application that demonstrates authentication and authorization.</p><p>This is an educational security gateway inspired by MCP tool-access principles. It uses FastAPI to demonstrate how a server can protect tools. It is not a complete MCP protocol implementation.</p><p>Our application will contain two tools:</p><ol><li>Read a report.</li><li>Update a report.</li></ol><p>The application will use three roles:</p><ul><li>Admin: Can read and update reports.</li><li>Developer: Can only read reports.</li><li>User: Can only read reports.</li></ul><h3>Step 1 — Install Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install fastapi uvicorn</pre><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named MCP_Security_Project.</p><pre>MCP_Security_Project/<br>│<br>├── app.py<br>└── requirements.txt</pre><h3>Step 3 — Create the Requirements File</h3><p>Open requirements.txt and add:</p><pre>fastapi<br>uvicorn</pre><h3>Step 4 — Create the Main Application</h3><p>Create a file named app.py.</p><pre>from fastapi import FastAPI, Header, HTTPException<br>from pydantic import BaseModel, Field</pre><pre>app = FastAPI(title=&quot;Secure MCP Tool Access Demo&quot;)</pre><pre># Demo credentials only.<br># Never use hardcoded API keys in a real application.<br>users = {<br>    &quot;admin-demo-key&quot;: {<br>        &quot;username&quot;: &quot;Admin&quot;,<br>        &quot;role&quot;: &quot;admin&quot;<br>    },<br>    &quot;developer-demo-key&quot;: {<br>        &quot;username&quot;: &quot;Developer&quot;,<br>        &quot;role&quot;: &quot;developer&quot;<br>    },<br>    &quot;user-demo-key&quot;: {<br>        &quot;username&quot;: &quot;User&quot;,<br>        &quot;role&quot;: &quot;user&quot;<br>    }<br>}</pre><pre># Demo report data<br>report = {<br>    &quot;title&quot;: &quot;Project Security Report&quot;,<br>    &quot;content&quot;: &quot;This is a sample project report.&quot;<br>}<br></pre><pre># Authenticate user<br>def authenticate(api_key):</pre><pre>    if not api_key or api_key not in users:<br>        raise HTTPException(<br>            status_code=401,<br>            detail=&quot;Invalid API key&quot;<br>        )</pre><pre>    return users[api_key]<br></pre><pre># Check permissions<br>def check_permission(user, required_roles):</pre><pre>    if user[&quot;role&quot;] not in required_roles:<br>        raise HTTPException(<br>            status_code=403,<br>            detail=&quot;Permission denied&quot;<br>        )<br></pre><pre># Input model<br>class ReportUpdate(BaseModel):</pre><pre>    content: str = Field(<br>        min_length=1,<br>        max_length=500<br>    )</pre><pre>    confirm: bool = False<br></pre><pre># Home endpoint<br>@app.get(&quot;/&quot;)<br>def home():</pre><pre>    return {<br>        &quot;message&quot;: &quot;Secure Tool Access API is running&quot;<br>    }<br></pre><pre># Read report tool<br>@app.get(&quot;/tools/read-report&quot;)<br>def read_report(x_api_key: str = Header(default=None)):</pre><pre>    user = authenticate(x_api_key)</pre><pre>    check_permission(<br>        user,<br>        [&quot;admin&quot;, &quot;developer&quot;, &quot;user&quot;]<br>    )</pre><pre>    return {<br>        &quot;message&quot;: &quot;Report accessed successfully&quot;,<br>        &quot;user&quot;: user[&quot;username&quot;],<br>        &quot;report&quot;: report<br>    }<br></pre><pre># Update report tool<br>@app.put(&quot;/tools/update-report&quot;)<br>def update_report(<br>    data: ReportUpdate,<br>    x_api_key: str = Header(default=None)<br>):</pre><pre>    user = authenticate(x_api_key)</pre><pre>    check_permission(<br>        user,<br>        [&quot;admin&quot;]<br>    )</pre><pre>    if not data.confirm:<br>        raise HTTPException(<br>            status_code=400,<br>            detail=&quot;Confirmation is required&quot;<br>        )</pre><pre>    report[&quot;content&quot;] = data.content</pre><pre>    return {<br>        &quot;message&quot;: &quot;Report updated successfully&quot;,<br>        &quot;updated_by&quot;: user[&quot;username&quot;],<br>        &quot;report&quot;: report<br>    }</pre><h3>Step 5 — Run the Application</h3><p>Open the terminal inside your project folder and execute:</p><pre>py -m uvicorn app:app --reload</pre><p>Open this URL:</p><p><a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a></p><p>FastAPI provides an interactive API testing page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*AwIJ3bnZ4r-C4WUpPvxYmw.png" /><figcaption><em>A secure tool workflow authenticates the user, checks permissions, validates inputs, and only then executes the requested operation.</em></figcaption></figure><h3>Step 6 — Test Authentication</h3><p>Open /tools/read-report.</p><p>Click <strong>Try it out</strong>.</p><p>Enter this header:</p><pre>x-api-key: admin-demo-key</pre><p>Click Execute.</p><p>Expected response:</p><pre>{<br>  &quot;message&quot;: &quot;Report accessed successfully&quot;,<br>  &quot;user&quot;: &quot;Admin&quot;,<br>  &quot;report&quot;: {<br>    &quot;title&quot;: &quot;Project Security Report&quot;,<br>    &quot;content&quot;: &quot;This is a sample project report.&quot;<br>  }<br>}</pre><h3>Step 7 — Test Authorization</h3><p>Now use this key:</p><pre>x-api-key: developer-demo-key</pre><p>The developer can read the report.</p><p>Next, open /tools/update-report and use the developer key.</p><p>The application should return:</p><pre>{<br>  &quot;detail&quot;: &quot;Permission denied&quot;<br>}</pre><p>This demonstrates that authentication alone does not grant permission to perform every operation.</p><h3>Step 8 — Test a Protected Update</h3><p>Open /tools/update-report.</p><p>Use the admin key:</p><pre>x-api-key: admin-demo-key</pre><p>Enter this request body:</p><pre>{<br>  &quot;content&quot;: &quot;The security review has been completed.&quot;,<br>  &quot;confirm&quot;: true<br>}</pre><p>Click Execute.</p><p>The report should be updated successfully.</p><p>If confirm is false, the application rejects the update.</p><h3>Step 9 — Test Invalid Authentication</h3><p>Try using an incorrect key:</p><pre>x-api-key: wrong-key</pre><p>The application returns:</p><pre>{<br>  &quot;detail&quot;: &quot;Invalid API key&quot;<br>}</pre><p>The application therefore demonstrates three important security checks:</p><ul><li>Authentication verifies identity.</li><li>Authorization checks permissions.</li><li>Input validation and confirmation protect tool operations.</li></ul><h3>9. Monitoring and Audit Logs</h3><p>Security does not end after authentication and authorization.</p><p>Developers should also monitor what happens during tool execution.</p><p>An audit log can record:</p><ul><li>User identity.</li><li>Tool name.</li><li>Request time.</li><li>Operation performed.</li><li>Access granted or denied.</li><li>Error details.</li></ul><p>For example, if a developer repeatedly attempts to update a restricted report, the application can record those denied requests for review.</p><p>Sensitive information such as API keys, passwords, and access tokens should never be written into logs.</p><p>Monitoring helps developers identify unusual activity and investigate security incidents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*tksnn-KrL9WrwFeJqlXMBw.png" /><figcaption><strong><em>Monitoring and audit logs provide visibility into tool requests, permission checks, failures, and suspicious activity.</em></strong></figcaption></figure><h3>10. Advantages of Secure MCP Integrations</h3><p><strong>Better Access Control:</strong> Only authorized users and tools can access protected resources.</p><p><strong>Improved Data Protection:</strong> Sensitive information receives appropriate protection.</p><p><strong>Reduced Security Risks:</strong> Input validation and permission checks help prevent unsafe operations.</p><p><strong>Greater Accountability:</strong> Audit logs help developers understand who accessed a tool and what operation was performed.</p><p><strong>Safer AI Automation:</strong> Security controls help reduce the impact of unintended AI tool calls.</p><h3>11. Challenges and Limitations</h3><p>Securing MCP integrations also introduces challenges.</p><ul><li><strong>Permission Management:</strong> Managing access across multiple tools and users can become complex.</li><li><strong>Credential Protection:</strong> API keys and tokens must be stored and handled securely.</li><li><strong>Prompt Injection:</strong> AI systems can still be influenced by malicious external content.</li><li><strong>Tool Trust:</strong> Developers must review the origin and behavior of connected tools.</li><li><strong>Monitoring:</strong> Large integrations can generate many events that require analysis.</li><li><strong>Human Approval:</strong> Sensitive operations need clear confirmation workflows.</li></ul><p>Our practical project is a learning demonstration. A real MCP deployment also needs protocol-compliant authentication where applicable, secure transport, proper token validation, server-side authorization, safe credential storage, and appropriate isolation.</p><h3>12. Future Scope</h3><p>MCP security can be improved further using advanced techniques:</p><ul><li><strong>OAuth 2.1 Integration:</strong> Use standardized authentication for remote protected services.</li><li><strong>Fine-Grained Permissions:</strong> Give individual tools specific read, write, or execute permissions.</li><li><strong>Secure Sandboxing:</strong> Isolate tools that execute commands or access files.</li><li><strong>Tool Verification:</strong> Review and verify tool definitions and server sources.</li><li><strong>Advanced Monitoring:</strong> Detect suspicious tool activity automatically.</li><li><strong>Human-in-the-Loop Approval:</strong> Require user confirmation for sensitive operations.</li></ul><p>These improvements can help organizations develop safer AI-powered systems.</p><h3>Conclusion: Powerful AI Connections Need Strong Security</h3><p>MCP makes it easier for AI applications to connect with external tools, data sources, and services.</p><p>However, these connections introduce security responsibilities.</p><p>Authentication verifies identity, authorization controls permissions, input validation protects tool operations, and monitoring helps developers detect suspicious activity.</p><p>In our practical project, we used Python and FastAPI to demonstrate how different user roles can access approved tools while restricted operations are rejected.</p><p>The most important lesson is that <strong>an AI application should not automatically trust every user, tool, or request. Every important operation needs appropriate security checks.</strong></p><p>By applying these principles, developers can build AI integrations that are more secure, controlled, and trustworthy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b31156b7289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CPU vs. GPU Inference: Choosing the Right Hardware for Machine Learning]]></title>
            <link>https://medium.com/@reddykowshik2008/cpu-vs-gpu-inference-choosing-the-right-hardware-for-machine-learning-768107c2cd78?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/768107c2cd78</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 08:45:33 GMT</pubDate>
            <atom:updated>2026-12-04T08:45:33.171Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding how CPUs and GPUs execute machine learning predictions, comparing their performance, and building a practical Python benchmarking project.</em></p><h3>Introduction: Does Machine Learning Need a Powerful GPU?</h3><p>Imagine building a machine learning application that predicts whether an email is spam or not.</p><p>The model works correctly on your laptop. But when thousands of users start sending requests, prediction speed becomes important.</p><p>You now have to decide: should the application use a CPU or a GPU?</p><p>Both are important hardware components, but they process information differently.</p><p>A CPU is designed to handle general-purpose tasks and complex sequential operations. A GPU contains many processing cores that can perform large numbers of similar operations in parallel.</p><p>Choosing the right hardware can affect prediction speed, throughput, cost, and resource usage.</p><p>In this article, we will understand CPU and GPU inference, compare their characteristics, and build a practical Python project using PyTorch to benchmark both devices when available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*xVbRrt_mQUwIGNDkv8c3uQ.png" /><figcaption><em>CPU vs. GPU inference demonstrates how different hardware architectures affect machine learning prediction performance.</em></figcaption></figure><h3>1. Understanding Machine Learning Inference</h3><p>Machine learning inference is the process of using a trained model to make predictions on new data.</p><p>For example, imagine a model trained to recognize different types of flowers.</p><p>The model learns patterns from training data. After training, it receives new flower measurements and predicts the flower category.</p><p>Inference follows these steps:</p><ol><li>Receive input data.</li><li>Prepare the input for the model.</li><li>Send the data to the trained model.</li><li>Perform the required calculations.</li><li>Generate the prediction.</li><li>Return the output.</li></ol><p>Inference can run on different hardware platforms, including CPUs, GPUs, and specialized AI accelerators.</p><p>The choice of hardware depends on the model size, workload, available resources, and application requirements.</p><h3>2. What Is CPU Inference?</h3><p>CPU stands for Central Processing Unit.</p><p>It is the main general-purpose processor in a computer. It handles operating system operations, application instructions, calculations, and many other tasks.</p><p>CPU inference means running a trained machine learning model using the computer’s CPU.</p><p>A CPU usually contains a relatively small number of powerful cores compared with a GPU. It is designed to handle different types of operations efficiently.</p><h3>Advantages of CPU Inference</h3><ul><li>Available on almost every computer.</li><li>Suitable for small and medium-sized models.</li><li>Does not require a dedicated graphics card.</li><li>Often simpler and cheaper to deploy.</li><li>Works well for many low-traffic applications.</li></ul><h3>Limitations</h3><ul><li>May process highly parallel workloads more slowly.</li><li>Can become a bottleneck with large prediction workloads.</li><li>May provide lower throughput for suitable large-scale neural network operations.</li></ul><p>CPU inference is useful for small applications, lightweight models, and situations where dedicated GPU hardware is unnecessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*U_x5VNWYhxVTExFa9bLE6Q.png" /><figcaption><em>CPU inference uses general-purpose processor cores to execute machine learning calculations and generate predictions.</em></figcaption></figure><h3>3. What Is GPU Inference?</h3><p>GPU stands for Graphics Processing Unit.</p><p>A GPU was originally designed to handle graphics calculations, but its parallel processing architecture also makes it useful for machine learning.</p><p>Many machine learning operations involve performing similar calculations across large amounts of data.</p><p>A GPU can execute many of these calculations simultaneously.</p><p>GPU inference means running a trained model using a GPU instead of a CPU.</p><h3>Advantages of GPU Inference</h3><ul><li>Supports highly parallel calculations.</li><li>Can provide high throughput for suitable workloads.</li><li>Useful for large neural networks.</li><li>Can accelerate image processing and deep learning.</li><li>Suitable for applications with demanding prediction workloads.</li></ul><h3>Limitations</h3><ul><li>Dedicated GPU hardware can be expensive.</li><li>Some operations may not benefit from GPU execution.</li><li>Moving data between CPU and GPU introduces overhead.</li><li>GPU memory is limited.</li><li>Applications require compatible software and hardware.</li></ul><p>GPU inference is especially useful for large neural networks and workloads that can take advantage of parallel processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*pUBN8aJBvRcApFyKNVwXZQ.png" /><figcaption><em>GPU inference uses parallel processing to accelerate suitable machine learning operations across large amounts of data.</em></figcaption></figure><h3>4. CPU vs. GPU Inference: Key Differences</h3><p>Both CPUs and GPUs can execute machine learning models, but they have different hardware designs.</p><p>FeatureCPUGPUMain purposeGeneral-purpose processingParallel processingProcessing coresFewer powerful coresMany smaller processing unitsWorkloadSequential and mixed tasksLarge parallel workloadsCostOften lower for basic deploymentDedicated hardware can be costlyPower usageDepends on processor and workloadCan be higher under heavy workloadsBest suited forSmall and moderate workloadsSuitable large parallel workloads</p><p>Neither hardware type is always better.</p><p>For a small model with very few requests, CPU inference may be sufficient. For a large neural network processing many inputs, GPU inference may provide significant benefits.</p><p>The actual result depends on the model, hardware, batch size, software configuration, and workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*btZWSWMWicLrWxFpm2727w.png" /></figure><h3>5. Understanding Inference Architecture</h3><p>A machine learning inference system contains several important components.</p><p><strong>Input Data:</strong> The information provided to the model.</p><p><strong>Trained Model:</strong> The model that has already learned patterns from training data.</p><p><strong>Hardware:</strong> The CPU or GPU used to execute the model.</p><p><strong>Prediction Engine:</strong> The software that performs the model calculations.</p><p><strong>Output:</strong> The prediction generated by the model.</p><p>The same trained model can often be executed on different hardware devices, provided the software framework and operations support those devices.</p><p>For example, PyTorch allows developers to move supported model computations between CPU and CUDA-enabled NVIDIA GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*2zq-WvzKwHronuFM0GrZqg.png" /><figcaption><em>A machine learning inference pipeline receives input data, executes a trained model on selected hardware, and produces prediction output.</em></figcaption></figure><h3>6. When Should We Choose CPU or GPU?</h3><p>Choosing hardware should depend on the application’s actual requirements.</p><h3>Choose CPU When:</h3><ul><li>The model is small.</li><li>The application receives fewer requests.</li><li>A dedicated GPU is unavailable.</li><li>Deployment cost is an important consideration.</li><li>The workload does not benefit much from parallel processing.</li></ul><h3>Choose GPU When:</h3><ul><li>The model contains large neural networks.</li><li>The application processes large batches.</li><li>High throughput is required.</li><li>The workload contains parallelizable calculations.</li><li>Compatible GPU hardware is available.</li></ul><p>For example, a small classification API may work efficiently on a CPU. A large image recognition application may benefit from GPU acceleration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*OYjxBk6brhZ5W9kw2TWekw.png" /><figcaption><em>CPU is often suitable for smaller workloads, while GPU can be beneficial for larger, parallel machine learning workloads.</em></figcaption></figure><h3>7. Practical Implementation: Benchmarking CPU and GPU Inference Using Python</h3><p>Now let’s create a practical project to compare CPU and GPU inference using the same neural network.</p><p>We will use PyTorch to:</p><ol><li>Create a simple neural network.</li><li>Generate sample input data.</li><li>Run inference using the CPU.</li><li>Run inference using a CUDA-enabled GPU if available.</li><li>Measure average batch latency.</li><li>Calculate throughput in samples per second.</li><li>Compare the results.</li></ol><p><strong>Important:</strong> A compatible NVIDIA GPU and CUDA-enabled PyTorch installation are required for the GPU test. If your computer does not have one, the program will still run the CPU benchmark and explain that GPU testing was skipped.</p><h3>Step 1 — Install Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install torch numpy pandas matplotlib</pre><p>For GPU testing, install a PyTorch build compatible with your NVIDIA GPU and supported CUDA version using the official PyTorch installation selector:</p><p><a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a></p><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named CPU_GPU_Inference_Project.</p><pre>CPU_GPU_Inference_Project/<br>│<br>├── benchmark.py<br>└── requirements.txt</pre><h3>Step 3 — Create requirements.txt</h3><p>Add the following libraries:</p><pre>torch<br>numpy<br>pandas<br>matplotlib</pre><h3>Step 4 — Create the Benchmarking Program</h3><p>Create a file named benchmark.py.</p><pre>import time<br>import torch<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>import torch.nn as nn<br></pre><pre># Create a simple neural network<br>class SimpleModel(nn.Module):</pre><pre>    def __init__(self):</pre><pre>        super().__init__()</pre><pre>        self.network = nn.Sequential(<br>            nn.Linear(100, 256),<br>            nn.ReLU(),<br>            nn.Linear(256, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 10)<br>        )</pre><pre>    def forward(self, x):</pre><pre>        return self.network(x)<br></pre><pre># Create model<br>model = SimpleModel()</pre><pre># Generate sample input<br>batch_size = 1024</pre><pre>input_data = torch.randn(batch_size, 100)</pre><pre># Detect GPU<br>devices = [&quot;cpu&quot;]</pre><pre>if torch.cuda.is_available():</pre><pre>    devices.append(&quot;cuda&quot;)</pre><pre>    print(&quot;GPU detected:&quot;, torch.cuda.get_device_name(0))</pre><pre>else:</pre><pre>    print(&quot;No CUDA GPU detected. CPU test only.&quot;)<br></pre><pre>results = []</pre><pre># Test each available device<br>for device in devices:</pre><pre>    print(&quot;\nTesting:&quot;, device)</pre><pre>    current_model = model.to(device)<br>    current_input = input_data.to(device)</pre><pre>    current_model.eval()</pre><pre>    # Warm-up<br>    with torch.no_grad():</pre><pre>        for _ in range(10):</pre><pre>            current_model(current_input)</pre><pre>        if device == &quot;cuda&quot;:</pre><pre>            torch.cuda.synchronize()</pre><pre>    # Benchmark<br>    start = time.perf_counter()</pre><pre>    with torch.no_grad():</pre><pre>        for _ in range(100):</pre><pre>            current_model(current_input)</pre><pre>        if device == &quot;cuda&quot;:</pre><pre>            torch.cuda.synchronize()</pre><pre>    end = time.perf_counter()</pre><pre>    total_time = end - start</pre><pre>    average_latency = total_time / 100</pre><pre>    throughput = (<br>        batch_size * 100<br>    ) / total_time</pre><pre>    results.append({<br>        &quot;Device&quot;: device.upper(),<br>        &quot;Average Latency (ms)&quot;: average_latency * 1000,<br>        &quot;Throughput (samples/sec)&quot;: throughput<br>    })</pre><pre>    print(<br>        &quot;Average Latency:&quot;,<br>        round(average_latency * 1000, 2),<br>        &quot;ms&quot;<br>    )</pre><pre>    print(<br>        &quot;Throughput:&quot;,<br>        round(throughput, 2),<br>        &quot;samples/sec&quot;<br>    )<br></pre><pre># Create results table<br>df = pd.DataFrame(results)</pre><pre>print(&quot;\nCPU vs GPU PERFORMANCE&quot;)<br>print(df)</pre><pre># Save results<br>df.to_csv(&quot;benchmark_results.csv&quot;, index=False)</pre><pre># Create latency graph<br>plt.figure()</pre><pre>plt.bar(<br>    df[&quot;Device&quot;],<br>    df[&quot;Average Latency (ms)&quot;]<br>)</pre><pre>plt.title(&quot;CPU vs GPU Inference Latency&quot;)<br>plt.xlabel(&quot;Device&quot;)<br>plt.ylabel(&quot;Average Batch Latency (ms)&quot;)</pre><pre>plt.savefig(&quot;latency_comparison.png&quot;)<br>plt.show()</pre><pre># Create throughput graph<br>plt.figure()</pre><pre>plt.bar(<br>    df[&quot;Device&quot;],<br>    df[&quot;Throughput (samples/sec)&quot;]<br>)</pre><pre>plt.title(&quot;CPU vs GPU Inference Throughput&quot;)<br>plt.xlabel(&quot;Device&quot;)<br>plt.ylabel(&quot;Samples per Second&quot;)</pre><pre>plt.savefig(&quot;throughput_comparison.png&quot;)<br>plt.show()</pre><pre>print(&quot;\nBenchmark completed!&quot;)<br>print(&quot;Results saved successfully!&quot;)</pre><h3>Step 5 — Run the Benchmarking Program</h3><p>Open the terminal inside the project folder and execute:</p><pre>py benchmark.py</pre><p>The program detects whether a CUDA-enabled NVIDIA GPU is available.</p><p>If it detects a GPU, it tests both CPU and GPU using the same model and input batch.</p><p>If no compatible GPU is available, it performs only the CPU test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*69Rkzrc-UvD3sbFCgy8biA.png" /><figcaption><em>The benchmarking process runs the same trained neural network on available hardware and records prediction time and throughput.</em></figcaption></figure><h3>Step 6 — Understand the Output</h3><p>The program produces a performance comparison.</p><p>Your actual results depend on your processor, GPU, batch size, PyTorch version, and system configuration.</p><p>Example output format:</p><pre>GPU detected: NVIDIA GPU</pre><pre>Testing: cpu</pre><pre>Average Latency: 52.00 ms<br>Throughput: 19692.31 samples/sec</pre><pre>Testing: cuda</pre><pre>Average Latency: 8.00 ms<br>Throughput: 1280000.00 samples/sec</pre><pre>CPU vs GPU PERFORMANCE</pre><pre>  Device   Average Latency<br>  CPU      52.00<br>  CUDA      8.00</pre><pre>Benchmark completed!<br>Results saved successfully!</pre><p><strong>These are illustrative example values, not actual measured results.</strong> Your program will print the real measurements from your computer.</p><p>The project also creates:</p><ul><li>benchmark_results.csv</li><li>latency_comparison.png</li><li>throughput_comparison.png</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*xkJNzztnl8VOzo0TTe-tOw.png" /><figcaption><em>Performance benchmarking compares CPU and GPU inference latency and throughput to identify which hardware is more suitable for a given workload.</em></figcaption></figure><h3>8. Understanding the Benchmarking Results</h3><p>Two important measurements help us compare the hardware.</p><h3>Average Latency</h3><p>Average latency measures the average time taken to complete one batch of predictions.</p><p>Lower latency generally means the batch finishes faster.</p><h3>Throughput</h3><p>Throughput measures how many individual samples the system processes per second.</p><p>Higher throughput means more samples are processed within the same period.</p><p>In our project, both measurements are calculated using the same neural network and batch size.</p><p>However, results from a single local experiment should not be treated as universal hardware performance rankings.</p><p>For a fair comparison, developers should also consider warm-up, synchronization, repeated measurements, memory usage, and different batch sizes.</p><h3>9. Advantages and Limitations</h3><h3>CPU Inference Advantages</h3><ul><li>Available on most computers.</li><li>Simple deployment.</li><li>Suitable for many small models.</li><li>Often economical for low-volume applications.</li></ul><h3>GPU Inference Advantages</h3><ul><li>Supports parallel computation.</li><li>Can improve throughput for suitable workloads.</li><li>Useful for large neural networks.</li><li>Suitable for demanding deep learning applications.</li></ul><h3>Limitations</h3><ul><li>GPU hardware can increase deployment cost.</li><li>Not every model operation benefits from GPU execution.</li><li>Data transfer between CPU and GPU can introduce overhead.</li><li>Results depend on software and hardware compatibility.</li><li>Local benchmark results may differ from production workloads.</li></ul><h3>10. Future Scope</h3><p>CPU and GPU inference continue to improve through hardware and software optimization.</p><p>Some important developments include:</p><ul><li><strong>Model Quantization:</strong> Reducing model precision and memory requirements.</li><li><strong>GPU Acceleration:</strong> Improving parallel computation.</li><li><strong>ONNX Runtime:</strong> Running supported models through optimized execution providers.</li><li><strong>Edge AI:</strong> Running machine learning models directly on local devices.</li><li><strong>Hardware Optimization:</strong> Selecting suitable processors for specific workloads.</li><li><strong>Automated Benchmarking:</strong> Comparing model performance across different hardware platforms.</li></ul><p>These developments help developers improve machine learning deployment efficiency.</p><h3>Conclusion: Choosing the Right Hardware Matters</h3><p>CPU and GPU inference are two important approaches to running machine learning models.</p><p>CPUs are useful for general-purpose processing and many smaller workloads. GPUs can accelerate suitable parallel workloads and provide higher throughput in demanding applications.</p><p>In our practical project, we used PyTorch to execute the same neural network on available hardware and measure inference latency and throughput.</p><p>The main lesson is that <strong>the best hardware is not always the most powerful hardware. It is the hardware that meets the application’s performance requirements at an appropriate cost.</strong></p><p>Understanding CPU and GPU inference helps developers make better decisions when deploying machine learning models in real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=768107c2cd78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Search: Building an AI-Powered Product Recommendation Engine]]></title>
            <link>https://medium.com/@reddykowshik2008/beyond-search-building-an-ai-powered-product-recommendation-engine-e1effa8d10c8?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1effa8d10c8</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 17:41:51 GMT</pubDate>
            <atom:updated>2026-12-01T17:41:51.577Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Machine Learning analyzes user preferences and product interactions to recommend relevant products and create more personalized shopping experiences.</em></p><h3>Introduction: Why Do Online Stores Recommend Products?</h3><p>Imagine opening an online shopping application to purchase a pair of running shoes. Before you finish browsing, the application starts suggesting sportswear, fitness watches, headphones, and other products that may interest you.</p><p>Have you ever wondered how these recommendations are generated?</p><p>Modern e-commerce platforms do more than display products. They analyze user interactions, browsing patterns, ratings, and purchase history to identify products that customers may find useful.</p><p>This technology is known as a <strong>Recommendation System</strong>.</p><p>Recommendation systems are an important application of Artificial Intelligence and Machine Learning. They help digital platforms personalize content and product discovery based on user preferences.</p><p>Instead of showing every product to every customer, a recommendation engine attempts to identify which products are most relevant to a particular user.</p><p>In this article, we will explore how recommendation systems work and build a practical AI-powered product recommendation engine using Python.</p><p>The implementation uses Pandas, Scikit-learn, cosine similarity, and Streamlit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*jGiBpi5-pag6CDig2z3zHw.png" /><figcaption><em>Figure 1. An AI-powered recommendation engine suggesting personalized products.</em></figcaption></figure><h3>1. Understanding Recommendation Systems</h3><p>A recommendation system is an information-filtering system that predicts which products, services, or content a user might prefer.</p><p>It analyzes available information and generates personalized suggestions.</p><p>For example, consider an online shopping platform.</p><ul><li>User A frequently purchases sports products.</li><li>User B regularly purchases electronic accessories.</li><li>User C prefers books and educational products.</li></ul><p>A recommendation engine can use these interaction patterns to suggest different products to each user.</p><p>The main objective is to improve product discovery by presenting relevant suggestions.</p><p>Recommendation systems are commonly used in:</p><ul><li>E-commerce platforms.</li><li>Music streaming applications.</li><li>Movie and entertainment platforms.</li><li>Online learning websites.</li><li>News and content platforms.</li></ul><h3>2. How Does a Recommendation System Work?</h3><p>A recommendation system generally follows a sequence of operations.</p><p><strong>Stage 1 — Data Collection:</strong> The system collects information such as product ratings, purchases, clicks, and browsing activity.</p><p><strong>Stage 2 — Data Processing:</strong> The collected information is cleaned and converted into a structured format.</p><p><strong>Stage 3 — Preference Analysis:</strong> The system analyzes user-product interactions to identify patterns.</p><p><strong>Stage 4 — Similarity Calculation:</strong> It identifies similar users or products using mathematical techniques.</p><p><strong>Stage 5 — Recommendation Generation:</strong> The system selects products that may interest the user.</p><p><strong>Stage 6 — Personalized Output:</strong> The recommended products are displayed to the user.</p><p>This process allows a platform to transform interaction data into personalized product suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*hpdNm9CXRyzru-nKUoqDPg.png" /><figcaption><em>Figure 2. The complete workflow of an AI-powered product recommendation system.</em></figcaption></figure><h3>3. Types of Recommendation Systems</h3><p>There are several approaches to generating recommendations. Three commonly used methods are:</p><h3>3.1 Content-Based Filtering</h3><p>Content-based filtering recommends products based on their characteristics and the user’s previous interests.</p><p>For example, if a customer frequently views wireless headphones, the system may recommend other headphones with similar features.</p><p>It focuses on product information such as:</p><ul><li>Category.</li><li>Brand.</li><li>Description.</li><li>Price range.</li><li>Product features.</li></ul><p>The main advantage is that recommendations can be generated using product information and individual user preferences.</p><h3>3.2 Collaborative Filtering</h3><p>Collaborative filtering uses interactions from multiple users to generate recommendations.</p><p>The underlying idea is that users with similar preferences may be interested in similar products.</p><p>For example:</p><ul><li>User A purchases headphones and running shoes.</li><li>User B purchases headphones and a smartwatch.</li><li>User A may receive a smartwatch recommendation based on User B’s interaction.</li></ul><p>Collaborative filtering does not necessarily require detailed product descriptions. It learns from patterns in user-item interactions.</p><h3>3.3 Hybrid Recommendation Systems</h3><p>Hybrid recommendation systems combine content-based and collaborative filtering.</p><p>This approach uses multiple sources of information to generate recommendations.</p><p>For example, an e-commerce application may combine product descriptions, customer ratings, and purchase history.</p><p>Hybrid systems can help overcome some limitations of using only one recommendation method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*v_RG6Si_6OSUQcNgUaYgaw.png" /><figcaption><em>Figure 3. Comparison of content-based, collaborative, and hybrid recommendation approaches.</em></figcaption></figure><h3>4. Understanding the Dataset</h3><p>To build a recommendation engine, we need information about how users interact with products.</p><p>For this project, we use a simple user-product interaction dataset.</p><p>The dataset contains four important columns:</p><p><strong>user_id:</strong> A unique identifier for each customer.</p><p><strong>item_id:</strong> A unique identifier for each product.</p><p><strong>rating:</strong> The rating given by a user to a product.</p><p><strong>timestamp:</strong> The date or time of the interaction.</p><p>A simplified example:</p><p>user_iditem_idrating101P1015101P1024102P1015102P1034103P1025</p><p>From these interactions, the system can identify relationships between users and products.</p><p>For this implementation, we will create a small sample dataset so that the project can run without downloading an external dataset.</p><p>For a larger experiment, real interaction data can be obtained from the Amazon Reviews datasets or another suitable e-commerce dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Xcr0olRkSNE5Pqkz3UeaoQ.png" /><figcaption><em>Figure 4. Example of user-product interaction data used for recommendations.</em></figcaption></figure><h3>5. The Machine Learning Technique: Collaborative Filtering</h3><p>For our practical implementation, we use item-based collaborative filtering.</p><p>The system identifies products that have similar rating patterns across users.</p><p>For example, if customers who rate Product A highly also tend to rate Product B highly, these products may be considered similar.</p><h3>Understanding Cosine Similarity</h3><p>Cosine similarity is a mathematical technique used to measure the similarity between two vectors.</p><p>It calculates the cosine of the angle between them.</p><p>The formula is:</p><p>[<br>\text{Cosine Similarity}(A,B)=<br>\frac{A\cdot B}{|A||B|}<br>]</p><p>Where:</p><ul><li>(A) and (B) represent two product vectors.</li><li>(A\cdot B) represents their dot product.</li><li>(|A|) and (|B|) represent their magnitudes.</li></ul><p>A value closer to 1 indicates a stronger similarity in direction.</p><p>In our recommendation engine, each product is represented by a vector of user ratings.</p><p>The model calculates similarity between products and uses these similarities to identify relevant recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*hCjloKAEGsoe44BnwQp5Dg.png" /><figcaption><em>Figure 5. Product similarity calculation using collaborative filtering.</em></figcaption></figure><h3>6. Technology Stack</h3><p>The project uses the following technologies:</p><p><strong>Python:</strong> Main programming language.</p><p><strong>Pandas:</strong> Organizes and processes user-product interaction data.</p><p><strong>NumPy:</strong> Supports numerical operations.</p><p><strong>Scikit-learn:</strong> Calculates cosine similarity between product vectors.</p><p><strong>Joblib:</strong> Saves and loads the recommendation model.</p><p><strong>Streamlit:</strong> Creates an interactive recommendation application.</p><h3>7. Practical Implementation: Building the Recommendation Engine</h3><p>Now let’s develop the actual application.</p><p>The project contains two main Python files:</p><ul><li>train.py – creates sample interaction data, calculates product similarity, and saves the recommendation model.</li><li>app.py – loads the saved model and displays personalized product recommendations.</li></ul><h3>Step 1: Install the Required Libraries</h3><p>Open the VS Code terminal and run:</p><pre>py -m pip install pandas numpy scikit-learn streamlit joblib</pre><h3>Step 2: Create the Project Structure</h3><p>Create a folder named Product_Recommendation_System.</p><p>Organize the files as follows:</p><pre>Product_Recommendation_System/<br>│<br>├── train.py<br>├── app.py<br>└── recommendation_model.pkl</pre><p>The model file will be created automatically when the training program runs.</p><h3>Step 3: Create the Sample Dataset and Train the Model</h3><p>Create a file named train.py.</p><p>The following code creates sample user-product interactions and trains an item-based recommendation model.</p><pre>import pandas as pd<br>import joblib</pre><pre>from sklearn.metrics.pairwise import cosine_similarity</pre><pre># Create sample interaction data<br>data = {<br>    &quot;user_id&quot;: [<br>        101, 101, 101, 102, 102, 102,<br>        103, 103, 103, 104, 104, 104,<br>        105, 105, 105, 106, 106, 106<br>    ],</pre><pre>    &quot;item_id&quot;: [<br>        &quot;Headphones&quot;, &quot;Shoes&quot;, &quot;Watch&quot;,<br>        &quot;Headphones&quot;, &quot;Watch&quot;, &quot;Backpack&quot;,<br>        &quot;Shoes&quot;, &quot;Backpack&quot;, &quot;Headphones&quot;,<br>        &quot;Watch&quot;, &quot;Headphones&quot;, &quot;Backpack&quot;,<br>        &quot;Shoes&quot;, &quot;Watch&quot;, &quot;Headphones&quot;,<br>        &quot;Backpack&quot;, &quot;Shoes&quot;, &quot;Watch&quot;<br>    ],</pre><pre>    &quot;rating&quot;: [<br>        5, 4, 5, 4, 5, 4,<br>        5, 4, 3, 5, 4, 5,<br>        4, 5, 4, 5, 4, 4<br>    ]<br>}</pre><pre>df = pd.DataFrame(data)</pre><pre>print(&quot;Dataset created successfully!&quot;)<br>print(df.head())</pre><pre># Create user-item matrix<br>user_item_matrix = df.pivot_table(<br>    index=&quot;user_id&quot;,<br>    columns=&quot;item_id&quot;,<br>    values=&quot;rating&quot;<br>).fillna(0)</pre><pre># Calculate item similarity<br>item_similarity = cosine_similarity(<br>    user_item_matrix.T<br>)</pre><pre># Convert similarity into DataFrame<br>similarity_df = pd.DataFrame(<br>    item_similarity,<br>    index=user_item_matrix.columns,<br>    columns=user_item_matrix.columns<br>)</pre><pre># Save model information<br>joblib.dump(<br>    {<br>        &quot;user_item_matrix&quot;: user_item_matrix,<br>        &quot;similarity&quot;: similarity_df<br>    },<br>    &quot;recommendation_model.pkl&quot;<br>)</pre><pre>print(&quot;\nRecommendation model created!&quot;)<br>print(&quot;\nProduct Similarity Matrix:&quot;)<br>print(similarity_df.round(2))</pre><h3>Understanding the Code</h3><p>The program first creates a sample dataset containing user IDs, product names, and ratings.</p><p>Next, pivot_table() converts the interaction data into a user-item matrix.</p><p>Each row represents a user, and each column represents a product.</p><p>Missing ratings are filled with zero because the user has not interacted with those products.</p><p>The cosine_similarity() function calculates similarity between product vectors.</p><p>Finally, the user-item matrix and similarity matrix are saved using Joblib.</p><p>This creates the information required by the recommendation application.</p><h3>Step 4: Create the Recommendation Function</h3><p>The recommendation function identifies products that are similar to the products a user has already rated.</p><p>Add the following code to a new file named app.py.</p><pre>import streamlit as st<br>import pandas as pd<br>import joblib</pre><pre>st.set_page_config(<br>    page_title=&quot;AI Product Recommendation Engine&quot;,<br>    page_icon=&quot;🛍️&quot;,<br>    layout=&quot;wide&quot;<br>)</pre><pre>st.title(&quot;🛍️ AI-Powered Product Recommendation Engine&quot;)</pre><pre>st.write(<br>    &quot;Discover personalized product suggestions &quot;<br>    &quot;using collaborative filtering.&quot;<br>)</pre><pre># Load saved model<br>@st.cache_resource<br>def load_model():</pre><pre>    return joblib.load(<br>        &quot;recommendation_model.pkl&quot;<br>    )</pre><pre>saved_data = load_model()</pre><pre>user_item_matrix = saved_data[&quot;user_item_matrix&quot;]<br>similarity_df = saved_data[&quot;similarity&quot;]</pre><pre># Recommendation function<br>def recommend_products(user_id, top_n=3):</pre><pre>    user_ratings = user_item_matrix.loc[user_id]</pre><pre>    purchased_products = user_ratings[<br>        user_ratings &gt; 0<br>    ]</pre><pre>    scores = {}</pre><pre>    for product, rating in purchased_products.items():</pre><pre>        similar_products = similarity_df[product]</pre><pre>        for other_product, similarity in similar_products.items():</pre><pre>            if user_ratings[other_product] == 0:</pre><pre>                scores[other_product] = (<br>                    scores.get(other_product, 0)<br>                    + similarity * rating<br>                )</pre><pre>    ranked_products = sorted(<br>        scores.items(),<br>        key=lambda x: x[1],<br>        reverse=True<br>    )</pre><pre>    return ranked_products[:top_n]</pre><h3>Understanding the Recommendation Function</h3><p>The function first identifies the products rated by the selected user.</p><p>It then checks how similar those products are to other products.</p><p>Products that the user has already rated are excluded from the recommendation list.</p><p>The similarity scores are weighted by the user’s ratings.</p><p>Finally, the products are sorted from highest to lowest score, and the top recommendations are returned.</p><p>This is a simple item-based collaborative filtering approach.</p><h3>Step 5: Build the Interactive Dashboard</h3><p>Add the following code below the recommendation function in app.py.</p><pre>st.subheader(&quot;Select a User&quot;)</pre><pre>user_ids = user_item_matrix.index.tolist()</pre><pre>selected_user = st.selectbox(<br>    &quot;Choose User ID&quot;,<br>    user_ids<br>)</pre><pre>if st.button(&quot;Generate Recommendations&quot;):</pre><pre>    recommendations = recommend_products(<br>        selected_user<br>    )</pre><pre>    st.subheader(<br>        f&quot;Recommended Products for User {selected_user}&quot;<br>    )</pre><pre>    if recommendations:</pre><pre>        for product, score in recommendations:</pre><pre>            st.success(<br>                f&quot;{product} | Recommendation Score: {score:.3f}&quot;<br>            )</pre><pre>    else:</pre><pre>        st.info(<br>            &quot;No new recommendations available for this user.&quot;<br>        )</pre><pre>st.divider()</pre><pre>st.subheader(&quot;Existing User Ratings&quot;)</pre><pre>st.dataframe(<br>    user_item_matrix<br>)</pre><p>The application displays a dropdown menu containing the available user IDs.</p><p>When the user selects an ID and clicks Generate Recommendations, the system identifies products that the user has not previously rated and ranks them according to similarity scores.</p><p>The dashboard also displays the user-item matrix for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*llIuPUmhWkjzrvnOhEjowg.png" /><figcaption><em>Figure 6. Personalized product recommendations generated for a selected user.</em></figcaption></figure><h3>Step 6: Run the Application</h3><p>First, execute the training program:</p><pre>py train.py</pre><p>This creates the saved recommendation model.</p><p>Next, start the Streamlit application:</p><pre>py -m streamlit run app.py</pre><p>The application will open in your browser.</p><p>Select a user ID and click Generate Recommendations.</p><p>The system will display products based on the selected user’s previous ratings.</p><h3>8. Understanding the Recommendation Results</h3><p>Suppose User 101 has rated the following products:</p><ul><li>Headphones — 5</li><li>Shoes — 4</li><li>Watch — 5</li></ul><p>The recommendation engine analyzes these interactions and calculates similarity scores between products.</p><p>It then identifies products that the user has not previously rated.</p><p>An illustrative output might look like this:</p><p>Recommended ProductRecommendation ScoreBackpack2.45Smart Speaker2.12Fitness Band1.89</p><p>These values are examples, not actual results from the sample code.</p><p>The actual recommendations depend on the interaction dataset and the calculated similarity matrix.</p><p>A recommendation score is a ranking value, not a probability that the user will purchase the product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*sRByKjyiemhd6ZW7gqIbmg.png" /><figcaption><em>Figure 7. Example metrics that can be used to evaluate a recommendation system.</em></figcaption></figure><h3>9. How Can We Evaluate a Recommendation System?</h3><p>A recommendation system should not be judged only by whether it produces a list of products.</p><p>We also need to understand how useful those recommendations are.</p><p>Some common evaluation measures include:</p><p><strong>Precision@K:</strong> Measures how many of the top K recommended items are relevant.</p><p><strong>Recall@K:</strong> Measures how many relevant items appear in the top K recommendations.</p><p><strong>Hit Rate:</strong> Measures whether at least one relevant item appears in the recommendation list.</p><p><strong>NDCG:</strong> Evaluates recommendation ranking quality by considering the positions of relevant items.</p><p>These metrics require a suitable evaluation dataset and a proper training/testing split.</p><p>For example, some user interactions can be held out during training. The system can then be evaluated on whether it recommends those held-out products.</p><p>Our small demonstration focuses on generating recommendations. It does not claim measured recommendation accuracy or ranking performance.</p><h3>10. Real-World Applications</h3><p>Recommendation systems are used across many digital industries.</p><p><strong>E-Commerce:</strong> Online stores recommend products based on customer preferences and interaction history.</p><p><strong>Music Streaming:</strong> Music platforms suggest songs and playlists based on listening behaviour.</p><p><strong>Video Streaming:</strong> Entertainment platforms recommend content based on viewing patterns.</p><p><strong>Online Education:</strong> Learning platforms suggest courses and learning resources based on student interests.</p><p><strong>News Applications:</strong> Content platforms recommend articles that may be relevant to individual readers.</p><p><strong>Digital Marketplaces:</strong> Marketplaces can suggest related products and services to improve product discovery.</p><p>These applications show how recommendation systems help users find relevant information among large collections of choices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*3puLg1jrrH9RcY5FJYuG-A.png" /><figcaption><em>Figure 8. Recommendation systems across e-commerce, entertainment, education, and digital platforms.</em></figcaption></figure><h3>11. Future Scope: Towards More Intelligent Recommendations</h3><p>The basic recommendation engine can be extended into a more advanced AI application.</p><p><strong>Hybrid Recommendation:</strong> Combine collaborative filtering with product descriptions, categories, and other product information.</p><p><strong>Deep Learning:</strong> Explore neural networks to learn complex user-product relationships.</p><p><strong>Real-Time Personalization:</strong> Update recommendations as users browse and interact with products.</p><p><strong>Context-Aware Recommendations:</strong> Consider factors such as time, location, and current shopping context when appropriate.</p><p><strong>Explainable Recommendations:</strong> Provide simple explanations for why a product was recommended.</p><p><strong>Scalable Recommendation Models:</strong> Explore approximate nearest-neighbour search and distributed processing for larger datasets.</p><p><strong>Multimodal Recommendations:</strong> Combine text, images, and product metadata to improve product understanding.</p><p>These improvements could make recommendation systems more flexible and useful for large digital platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*7aajl1Ys0ohwBAXMduYAlg.png" /><figcaption><em>Figure 9. The future of personalized recommendations across connected digital platforms.</em></figcaption></figure><h3>12.Conclusion: Making Product Discovery More Personal</h3><p>Recommendation systems demonstrate how Artificial Intelligence can transform large collections of products into personalized discovery experiences.</p><p>By analyzing user-product interactions and calculating similarity between products, a recommendation engine can identify items that may interest individual customers.</p><p>In this project, we explored item-based collaborative filtering using Python, Pandas, Scikit-learn, and Streamlit.</p><p>The implementation demonstrates the complete process, from creating interaction data and calculating product similarities to generating personalized recommendations through an interactive application.</p><p>Although the prototype uses a small sample dataset, the same basic concepts can be extended to larger e-commerce datasets and more advanced recommendation algorithms.</p><p>The future of digital shopping is not only about helping customers search for products. It is also about helping them discover products they may not have found on their own.</p><p><strong>The goal of a smarter recommendation system is simple: show the right product to the right user at the right time.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1effa8d10c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Traffic Lights: Building an AI-Powered Traffic Congestion Prediction System]]></title>
            <link>https://medium.com/@reddykowshik2008/beyond-traffic-lights-building-an-ai-powered-traffic-congestion-prediction-system-e5b3c09e2d89?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5b3c09e2d89</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 17:40:44 GMT</pubDate>
            <atom:updated>2026-12-01T17:40:44.581Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Machine Learning can analyze traffic conditions, predict congestion levels, and support smarter urban transportation.</em></p><h3>Introduction: Can AI Predict a Traffic Jam Before It Happens?</h3><p>Imagine leaving home for college or work. Your usual route takes 25 minutes, but today the journey takes almost an hour because of unexpected traffic congestion.</p><p>Traffic congestion is one of the major challenges faced by modern cities. Increasing vehicle ownership, population growth, road construction, accidents, and changing travel patterns all contribute to crowded roads.</p><p>Traditional traffic management systems often depend on fixed schedules, manual monitoring, and existing traffic information. These methods are useful, but they may not always respond quickly to changing road conditions.</p><p>This creates an opportunity for Artificial Intelligence.</p><p>What if a system could analyze traffic information and estimate whether a road is likely to experience low, moderate, or heavy congestion?</p><p>This is the idea behind an <strong>AI-Powered Traffic Congestion Prediction System</strong>.</p><p>In this project, we explore how Machine Learning can identify patterns in traffic data and predict congestion levels using Python.</p><p>We will build a practical prototype using Pandas, Scikit-learn, Random Forest Classification, and Streamlit.</p><p>The objective is to demonstrate how data-driven predictions can support smarter transportation planning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*saMj8o5WjrGUzjGsTkJMBw.png" /><figcaption><em>Figure 1. AI-powered traffic prediction for intelligent urban transportation.</em></figcaption></figure><h3>1. Understanding Traffic Congestion Prediction</h3><p>Traffic congestion prediction is the process of estimating future traffic conditions using historical and current traffic information.</p><p>A prediction system analyzes different factors that influence road traffic.</p><p>Some important factors include:</p><ul><li>Number of vehicles on the road.</li><li>Average vehicle speed.</li><li>Time of the day.</li><li>Day of the week.</li><li>Weather conditions.</li><li>Road type and capacity.</li><li>Previous traffic patterns.</li></ul><p>For example, traffic conditions during morning and evening office hours may be different from those during late-night hours.</p><p>A machine-learning model can learn relationships between these factors and historical congestion labels.</p><p>Based on the learned patterns, it can classify traffic conditions into categories such as:</p><p><strong>Low Congestion:</strong> Vehicles can generally move without major delays.</p><p><strong>Moderate Congestion:</strong> Traffic is slower, with some delays.</p><p><strong>Heavy Congestion:</strong> Roads experience significant traffic buildup and reduced movement.</p><p>The main goal is to provide an early indication of traffic conditions so that transportation decisions can be made more effectively.</p><h3>2. How Does an AI Traffic Prediction System Work?</h3><p>An AI-powered traffic prediction system follows a structured workflow.</p><p><strong>Stage 1 — Data Collection:</strong> Collect traffic information from sensors, cameras, GPS devices, and historical traffic datasets.</p><p><strong>Stage 2 — Data Preprocessing:</strong> Clean the collected data, handle missing values, and convert information into a suitable format.</p><p><strong>Stage 3 — Feature Selection:</strong> Identify important traffic-related features such as vehicle count, average speed, and time.</p><p><strong>Stage 4 — Model Training:</strong> Train a machine-learning algorithm using historical traffic records.</p><p><strong>Stage 5 — Prediction:</strong> Provide traffic conditions to the trained model and generate a congestion prediction.</p><p><strong>Stage 6 — Visualization:</strong> Display the predicted congestion level through an interactive dashboard.</p><p>This workflow transforms traffic information into useful predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*VHsPvKdIMpNYI-NzZGUbOg.png" /><figcaption><em>Figure 2. Connected traffic sensors and monitoring systems collect information from roads.</em></figcaption></figure><h3>3. Understanding Traffic Data</h3><p>The quality of a prediction system depends heavily on the information used to train it.</p><p>Traffic datasets can contain different types of information.</p><p>For our project, we consider the following features:</p><p><strong>Vehicle Count:</strong> The number of vehicles recorded during a particular time interval.</p><p><strong>Average Speed:</strong> The average speed of vehicles travelling on a road.</p><p><strong>Hour:</strong> The hour of the day when the traffic was recorded.</p><p><strong>Day of Week:</strong> The day on which the traffic observation was collected.</p><p><strong>Weather:</strong> The weather condition during the observation.</p><p><strong>Road Type:</strong> The type of road, such as a highway or urban road.</p><p><strong>Congestion Level:</strong> The target variable representing the traffic condition.</p><p>A simplified dataset might look like this:</p><p>Vehicle CountAverage SpeedHourWeatherCongestion255510ClearLow60359RainyModerate1101518ClearHeavy852217RainyHeavy</p><p>These values are illustrative examples.</p><p>For the practical demonstration, we will generate a synthetic dataset so the project can run without downloading a large external dataset.</p><p>For real-world research, actual traffic observations should be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*EfA6gXTXV3KsrKWY76WOPg.png" /><figcaption><em>Figure 3. Example of structured traffic data used for machine-learning predictions.</em></figcaption></figure><h3>4. Data Preprocessing: Preparing Traffic Information</h3><p>Raw traffic information may contain missing values, inconsistent formats, duplicate records, and incorrect measurements.</p><p>Before training a machine-learning model, the data must be prepared.</p><p>The preprocessing process includes:</p><p><strong>Removing Duplicate Records:</strong> Prevents repeated observations from unnecessarily influencing training.</p><p><strong>Handling Missing Values:</strong> Fills or removes incomplete records.</p><p><strong>Converting Categorical Data:</strong> Converts weather and road-type information into numerical representations.</p><p><strong>Selecting Relevant Features:</strong> Keeps the information needed for prediction.</p><p><strong>Splitting the Dataset:</strong> Separates training and testing data to evaluate model performance.</p><p>Proper preprocessing helps create a more reliable machine-learning pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*uU6-Sy-dk4eHC1-9GcqgOg.png" /><figcaption><em>Figure 4. Traffic data preprocessing and preparation workflow.</em></figcaption></figure><h3>5. Choosing the Machine Learning Algorithm</h3><p>For this project, we use <strong>Random Forest Classification</strong>.</p><p>Random Forest is an ensemble machine-learning algorithm that combines multiple decision trees to produce a prediction.</p><p>Each decision tree learns patterns from the training data.</p><p>When a new traffic record is supplied, the trees independently predict a congestion category.</p><p>The Random Forest combines their predictions and selects the final class.</p><h3>How Random Forest Works</h3><p><strong>Step 1 — Input Data:</strong> The model receives traffic features such as vehicle count, average speed, and hour.</p><p><strong>Step 2 — Decision Tree Creation:</strong> Multiple decision trees are trained using different samples and feature selections.</p><p><strong>Step 3 — Pattern Learning:</strong> Each tree learns relationships between traffic conditions and congestion levels.</p><p><strong>Step 4 — Prediction:</strong> Each tree predicts a congestion category for new traffic information.</p><p><strong>Step 5 — Final Classification:</strong> The model combines the individual predictions to produce the final result.</p><p>Random Forest is useful for this project because it can learn nonlinear relationships and work with a mixture of numerical and encoded categorical features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*tNRjdP8_inE3JUmrWjUipg.png" /><figcaption><em>Figure 5. Random Forest classification architecture for traffic congestion prediction.</em></figcaption></figure><h3>6. Technology Stack</h3><p>The project uses the following technologies:</p><p><strong>Python:</strong> Main programming language.</p><p><strong>Pandas:</strong> Loads, organizes, and processes traffic data.</p><p><strong>NumPy:</strong> Supports numerical operations.</p><p><strong>Scikit-learn:</strong> Provides preprocessing tools, Random Forest classification, and model evaluation.</p><p><strong>Joblib:</strong> Saves and loads the trained model.</p><p><strong>Streamlit:</strong> Creates an interactive traffic prediction dashboard.</p><p><strong>Matplotlib:</strong> Can be used for additional performance visualizations.</p><h3>7. Practical Implementation: Building the Prediction System</h3><p>Now let’s develop the actual application.</p><p>The project contains two main Python files:</p><ul><li>train.py – creates the sample dataset, preprocesses the data, trains the model, evaluates it, and saves the trained pipeline.</li><li>app.py – loads the trained model and predicts traffic congestion using user-provided information.</li></ul><h3>Step 1: Install the Required Libraries</h3><p>Open the VS Code terminal and run:</p><pre>py -m pip install pandas numpy scikit-learn streamlit joblib</pre><h3>Step 2: Create the Project Structure</h3><p>Create a folder named Traffic_Congestion_Prediction.</p><p>Organize the files as follows:</p><pre>Traffic_Congestion_Prediction/<br>│<br>├── train.py<br>├── app.py<br>└── traffic_model.pkl</pre><p>The model file will be generated automatically after training.</p><h3>Step 3: Create and Prepare the Dataset</h3><p>Create a Python file named train.py.</p><p>The following code generates a demonstration dataset containing traffic information.</p><pre>import pandas as pd<br>import numpy as np<br>import joblib</pre><pre>from sklearn.model_selection import train_test_split<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import OneHotEncoder<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import (<br>    accuracy_score,<br>    classification_report,<br>    confusion_matrix<br>)</pre><pre># Generate sample traffic data<br>np.random.seed(42)</pre><pre>n = 2000</pre><pre>data = pd.DataFrame({<br>    &quot;vehicle_count&quot;: np.random.randint(10, 151, n),<br>    &quot;average_speed&quot;: np.random.randint(10, 81, n),<br>    &quot;hour&quot;: np.random.randint(0, 24, n),<br>    &quot;day_of_week&quot;: np.random.randint(0, 7, n),<br>    &quot;weather&quot;: np.random.choice(<br>        [&quot;Clear&quot;, &quot;Rainy&quot;, &quot;Foggy&quot;],<br>        n<br>    ),<br>    &quot;road_type&quot;: np.random.choice(<br>        [&quot;Highway&quot;, &quot;Urban&quot;, &quot;Residential&quot;],<br>        n<br>    )<br>})</pre><pre># Create demonstration congestion labels<br>traffic_score = (<br>    data[&quot;vehicle_count&quot;] * 0.6<br>    - data[&quot;average_speed&quot;] * 0.8<br>    + data[&quot;hour&quot;].apply(<br>        lambda x: 15 if x in [8, 9, 17, 18, 19] else 0<br>    )<br>    + data[&quot;weather&quot;].map({<br>        &quot;Clear&quot;: 0,<br>        &quot;Rainy&quot;: 8,<br>        &quot;Foggy&quot;: 12<br>    })<br>    + data[&quot;road_type&quot;].map({<br>        &quot;Highway&quot;: -5,<br>        &quot;Urban&quot;: 8,<br>        &quot;Residential&quot;: 0<br>    })<br>)</pre><pre>data[&quot;congestion&quot;] = pd.cut(<br>    traffic_score,<br>    bins=[-float(&quot;inf&quot;), 30, 65, float(&quot;inf&quot;)],<br>    labels=[&quot;Low&quot;, &quot;Moderate&quot;, &quot;Heavy&quot;]<br>)</pre><pre>print(&quot;Traffic dataset created successfully!&quot;)<br>print(data.head())</pre><pre>print(&quot;\nCongestion Distribution:&quot;)<br>print(data[&quot;congestion&quot;].value_counts())</pre><h3>Understanding the Dataset Code</h3><p>The program first imports the required Python libraries.</p><p>It generates 2,000 sample traffic records using NumPy.</p><p>Each record contains vehicle count, average speed, hour, day of the week, weather, and road type.</p><p>A demonstration traffic score is calculated using these variables.</p><p>The pd.cut() function converts the score into three congestion categories:</p><ul><li>Low</li><li>Moderate</li><li>Heavy</li></ul><p>This creates a labelled dataset that can be used to demonstrate supervised machine learning.</p><p><strong>Important:</strong> These labels are generated using an artificial formula. They are not measured real-world traffic conditions.</p><h3>Step 4: Preprocess the Data and Train the Model</h3><p>Add the following code below the previous section in train.py.</p><pre># Separate features and target<br>X = data.drop(columns=[&quot;congestion&quot;])<br>y = data[&quot;congestion&quot;].astype(str)</pre><pre># Identify numerical and categorical columns<br>numerical_features = [<br>    &quot;vehicle_count&quot;,<br>    &quot;average_speed&quot;,<br>    &quot;hour&quot;,<br>    &quot;day_of_week&quot;<br>]</pre><pre>categorical_features = [<br>    &quot;weather&quot;,<br>    &quot;road_type&quot;<br>]</pre><pre># Create preprocessing pipeline<br>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (<br>            &quot;num&quot;,<br>            SimpleImputer(strategy=&quot;median&quot;),<br>            numerical_features<br>        ),<br>        (<br>            &quot;cat&quot;,<br>            Pipeline([<br>                (<br>                    &quot;imputer&quot;,<br>                    SimpleImputer(strategy=&quot;most_frequent&quot;)<br>                ),<br>                (<br>                    &quot;encoder&quot;,<br>                    OneHotEncoder(handle_unknown=&quot;ignore&quot;)<br>                )<br>            ]),<br>            categorical_features<br>        )<br>    ]<br>)</pre><pre># Create complete machine-learning pipeline<br>model = Pipeline([<br>    (&quot;preprocessor&quot;, preprocessor),<br>    (<br>        &quot;classifier&quot;,<br>        RandomForestClassifier(<br>            n_estimators=100,<br>            random_state=42,<br>            class_weight=&quot;balanced&quot;<br>        )<br>    )<br>])</pre><pre># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y<br>)</pre><pre># Train the model<br>model.fit(X_train, y_train)</pre><pre># Generate predictions<br>predictions = model.predict(X_test)</pre><pre># Evaluate model<br>accuracy = accuracy_score(<br>    y_test,<br>    predictions<br>)</pre><pre>print(&quot;\nModel Training Completed!&quot;)</pre><pre>print(<br>    &quot;Accuracy:&quot;,<br>    round(accuracy * 100, 2),<br>    &quot;%&quot;<br>)</pre><pre>print(&quot;\nClassification Report:&quot;)<br>print(<br>    classification_report(<br>        y_test,<br>        predictions,<br>        zero_division=0<br>    )<br>)</pre><pre>print(&quot;\nConfusion Matrix:&quot;)<br>print(<br>    confusion_matrix(<br>        y_test,<br>        predictions<br>    )<br>)</pre><pre># Save trained model<br>joblib.dump(<br>    model,<br>    &quot;traffic_model.pkl&quot;<br>)</pre><pre>print(&quot;\nModel saved successfully!&quot;)</pre><h3>Understanding the Training Process</h3><p>The program separates the input features from the target congestion category.</p><p>The ColumnTransformer applies different preprocessing operations to numerical and categorical columns.</p><p>Numerical missing values are handled using median imputation.</p><p>Categorical values are converted into numerical features using One-Hot Encoding.</p><p>The train_test_split() function divides the data into training and testing portions.</p><p>The Random Forest classifier learns from the training data and is evaluated using the testing data.</p><p>Finally, the complete pipeline is saved using Joblib.</p><p>Saving the complete pipeline ensures that the same preprocessing operations are applied when making predictions later.</p><h3>Step 5: Build the Streamlit Prediction Application</h3><p>Create another file named app.py.</p><p>The application allows users to enter traffic information and receive a predicted congestion category.</p><pre>import streamlit as st<br>import pandas as pd<br>import joblib</pre><pre>st.set_page_config(<br>    page_title=&quot;AI Traffic Prediction&quot;,<br>    page_icon=&quot;🚦&quot;,<br>    layout=&quot;wide&quot;<br>)</pre><pre>st.title(&quot;🚦 AI-Powered Traffic Congestion Prediction&quot;)</pre><pre>st.write(<br>    &quot;Enter traffic conditions to predict &quot;<br>    &quot;the expected congestion level.&quot;<br>)</pre><pre># Load the trained model<br>@st.cache_resource<br>def load_model():<br>    return joblib.load(&quot;traffic_model.pkl&quot;)</pre><pre>model = load_model()</pre><pre>st.subheader(&quot;Enter Traffic Information&quot;)</pre><pre>col1, col2 = st.columns(2)</pre><pre>with col1:</pre><pre>    vehicle_count = st.slider(<br>        &quot;Number of Vehicles&quot;,<br>        0,<br>        200,<br>        60<br>    )</pre><pre>    average_speed = st.slider(<br>        &quot;Average Speed (km/h)&quot;,<br>        0,<br>        120,<br>        40<br>    )</pre><pre>    hour = st.slider(<br>        &quot;Hour of the Day&quot;,<br>        0,<br>        23,<br>        9<br>    )</pre><pre>with col2:</pre><pre>    day_of_week = st.selectbox(<br>        &quot;Day of the Week&quot;,<br>        list(range(7))<br>    )</pre><pre>    weather = st.selectbox(<br>        &quot;Weather Condition&quot;,<br>        [&quot;Clear&quot;, &quot;Rainy&quot;, &quot;Foggy&quot;]<br>    )</pre><pre>    road_type = st.selectbox(<br>        &quot;Road Type&quot;,<br>        [&quot;Highway&quot;, &quot;Urban&quot;, &quot;Residential&quot;]<br>    )</pre><pre># Predict congestion<br>if st.button(&quot;Predict Traffic Congestion&quot;):</pre><pre>    input_data = pd.DataFrame([{<br>        &quot;vehicle_count&quot;: vehicle_count,<br>        &quot;average_speed&quot;: average_speed,<br>        &quot;hour&quot;: hour,<br>        &quot;day_of_week&quot;: day_of_week,<br>        &quot;weather&quot;: weather,<br>        &quot;road_type&quot;: road_type<br>    }])</pre><pre>    prediction = model.predict(input_data)[0]</pre><pre>    st.subheader(&quot;Prediction Result&quot;)</pre><pre>    if prediction == &quot;Low&quot;:</pre><pre>        st.success(<br>            &quot;Low Congestion: Traffic is expected to be relatively smooth.&quot;<br>        )</pre><pre>    elif prediction == &quot;Moderate&quot;:</pre><pre>        st.warning(<br>            &quot;Moderate Congestion: Some traffic delays may occur.&quot;<br>        )</pre><pre>    else:</pre><pre>        st.error(<br>            &quot;Heavy Congestion: Significant traffic delays may occur.&quot;<br>        )</pre><pre>    st.write(<br>        &quot;Predicted Traffic Level:&quot;,<br>        prediction<br>    )</pre><h3>Understanding the Application</h3><p>The application first loads the saved Random Forest model.</p><p>The user enters traffic information using sliders and dropdown menus.</p><p>The application creates a DataFrame containing the entered information.</p><p>The trained model processes the input and predicts one of three congestion categories.</p><p>The result is displayed using Streamlit status messages.</p><p>This makes the prediction system interactive and easy to demonstrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*jjaq7Nb8Bp1qfTwGL_sqMQ.png" /><figcaption><em>Figure 6. Example of a model evaluation dashboard showing classification performance.</em></figcaption></figure><h3>Step 6: Run the Project</h3><p>First, train the model:</p><pre>py train.py</pre><p>After successful training, run the Streamlit application:</p><pre>py -m streamlit run app.py</pre><p>Open the local application in your browser.</p><p>Enter the traffic information and click <strong>Predict Traffic Congestion</strong>.</p><p>The application will display the predicted traffic category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*RZO2lixqNwbF1Ze3nMsRtA.png" /><figcaption><em>Figure 7. An interactive dashboard for entering traffic information and viewing predictions.</em></figcaption></figure><h3>8. Understanding the Prediction Results</h3><p>Suppose a user enters the following information:</p><ul><li>Number of vehicles: 120</li><li>Average speed: 15 km/h</li><li>Hour: 18</li><li>Weather: Rainy</li><li>Road type: Urban</li></ul><p>The system processes these values and predicts a congestion category.</p><p>An illustrative result might be:</p><p><strong>Predicted Traffic Level: Heavy</strong></p><p>This result indicates that the input resembles traffic patterns associated with the Heavy category in the training dataset.</p><p>The actual prediction depends on the trained model.</p><p>Because this project uses synthetic data, the output demonstrates the machine-learning workflow rather than providing a reliable prediction for a real road.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*3UPRWppPOMXgc3dXB_mrdg.png" /><figcaption><em>Figure 8. Illustrative traffic congestion heatmap highlighting areas with different traffic intensities.</em></figcaption></figure><h3>9. Evaluating the Machine Learning Model</h3><p>A machine-learning model should be evaluated before it is used for practical decision-making.</p><p>For our project, we use the following evaluation measures:</p><p><strong>Accuracy:</strong> Measures the percentage of correctly classified traffic records.</p><p><strong>Precision:</strong> Measures how many predictions for a particular congestion category were correct.</p><p><strong>Recall:</strong> Measures how many actual records belonging to a category were correctly identified.</p><p><strong>F1-Score:</strong> Combines precision and recall into a single measure.</p><p><strong>Confusion Matrix:</strong> Displays correct and incorrect predictions for each congestion category.</p><p>These measures help us understand how well the model distinguishes between Low, Moderate, and Heavy traffic conditions.</p><p>However, because our demonstration labels are generated from a predefined formula, good evaluation results do not prove that the model can accurately predict real-world traffic.</p><p>For a realistic system, evaluation must use actual traffic observations and preferably test on later time periods that were not included during training.</p><h3>10. Real-World Applications</h3><p>AI-based traffic prediction can support different transportation activities.</p><p><strong>Smart City Management:</strong> City authorities can use traffic predictions to understand congestion patterns and plan road improvements.</p><p><strong>Navigation Applications:</strong> Traffic predictions can help navigation services estimate travel conditions and explore alternative routes.</p><p><strong>Public Transportation:</strong> Transport authorities can study traffic patterns when planning bus schedules and routes.</p><p><strong>Emergency Services:</strong> Traffic information can help emergency response teams understand road conditions and plan journeys.</p><p><strong>Event Management:</strong> Traffic predictions can support planning around stadiums, festivals, exhibitions, and other large public events.</p><p><strong>Urban Planning:</strong> Historical traffic analysis can help identify areas that may require better road infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*nevpL-MA6traxDjAcXn5SQ.png" /><figcaption><em>Figure 9. The future of intelligent transportation with connected roads and smart mobility systems.</em></figcaption></figure><h3>11. Challenges and Limitations</h3><p>Although AI can support traffic prediction, developing a reliable system involves several challenges.</p><p><strong>Data Availability:</strong> Accurate predictions require sufficient traffic observations from different roads and time periods.</p><p><strong>Changing Traffic Conditions:</strong> Accidents, road closures, construction, and public events can suddenly change traffic patterns.</p><p><strong>Weather Influence:</strong> Heavy rainfall, fog, and other weather conditions may affect vehicle movement.</p><p><strong>Model Accuracy:</strong> A model trained on one location may not perform equally well in another city.</p><p><strong>Real-Time Processing:</strong> Processing continuous traffic information requires suitable infrastructure and efficient algorithms.</p><p><strong>Data Quality:</strong> Incorrect sensor readings and missing observations can reduce prediction reliability.</p><p><strong>Privacy:</strong> Traffic monitoring systems must handle location and vehicle-related information responsibly.</p><p>These challenges show that building a practical traffic prediction platform requires more than simply training a machine-learning model.</p><h3>12. Future Scope: Towards Intelligent Transportation</h3><p>The current implementation is a basic prediction prototype. It can be extended into a more advanced intelligent transportation platform.</p><p><strong>Real-Time Traffic Data:</strong> Integrate traffic sensors, GPS information, or supported traffic data APIs.</p><p><strong>Traffic Forecasting:</strong> Predict traffic conditions for future time intervals instead of only classifying the current input.</p><p><strong>Deep Learning:</strong> Explore LSTM and other time-series models for learning complex traffic patterns.</p><p><strong>Traffic Visualization:</strong> Display road congestion levels on interactive maps.</p><p><strong>Accident Detection:</strong> Integrate incident information to improve traffic analysis.</p><p><strong>Route Optimization:</strong> Combine traffic predictions with route-planning algorithms to identify potentially faster journeys.</p><p><strong>Adaptive Traffic Signals:</strong> Explore systems that adjust traffic signal timing based on traffic demand.</p><p>These developments could help create more intelligent, responsive, and efficient transportation systems.</p><h3>Conclusion: Building Smarter Roads with Artificial Intelligence</h3><p>Traffic congestion is a complex challenge that affects daily travel, business operations, and urban development.</p><p>Artificial Intelligence provides an opportunity to analyze traffic information and identify patterns that may not be easy to recognize through manual observation.</p><p>In this project, we explored how Python, Pandas, Scikit-learn, Random Forest Classification, and Streamlit can be combined to build a traffic congestion prediction prototype.</p><p>The implementation demonstrates the complete machine-learning workflow, from generating and preparing data to training a model and displaying predictions through an interactive dashboard.</p><p>Although the current version uses synthetic data, the same architecture can be extended using real traffic observations and real-time data sources.</p><p>The future of transportation will not depend only on building wider roads or adding more traffic signals. It will also depend on using data intelligently to understand how people and vehicles move.</p><p><strong>The goal is not simply to manage traffic after congestion occurs, but to use intelligent predictions to make transportation smarter.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5b3c09e2d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Spam Folder: Building an AI-Powered Phishing Email Detection System]]></title>
            <link>https://medium.com/@reddykowshik2008/beyond-the-spam-folder-building-an-ai-powered-phishing-email-detection-system-6488537596da?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/6488537596da</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 17:40:29 GMT</pubDate>
            <atom:updated>2026-12-01T17:40:29.636Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Natural Language Processing and Machine Learning can identify suspicious emails and help users recognize potential cyber threats.</em></p><h3>Introduction: When an Email Becomes a Security Threat</h3><p>An email arrives in your inbox.</p><p>It appears to come from your bank. The message says that your account will be suspended unless you verify your details immediately. It includes a link and asks you to sign in.</p><p>The message looks convincing. The sender’s name appears familiar, the language sounds professional, and the warning creates a sense of urgency.</p><p>But there is a problem: the email is fake.</p><p>This is an example of phishing, a cyberattack in which attackers attempt to trick people into revealing sensitive information, clicking malicious links, or downloading harmful files.</p><p>Traditional spam filters can identify many unwanted messages, but phishing techniques continue to evolve. Attackers frequently change their wording, impersonate trusted organizations, and create messages designed to look legitimate.</p><p>This raises an important question:</p><p><strong>Can Artificial Intelligence help identify suspicious emails by understanding the language and patterns used in them?</strong></p><p>Machine Learning and Natural Language Processing provide a way to explore this problem.</p><p>In this project, we build an <strong>AI-Powered Phishing Email Detection System</strong> using Python. The system analyzes email text and classifies messages as either phishing or legitimate.</p><p>We will use TF-IDF for text feature extraction, Logistic Regression for classification, and Streamlit to create an interactive application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*aLvQfNHMRMHAFZCYcsFm3Q.png" /><figcaption><em>Figure 1. AI-powered email security system designed to identify suspicious messages.</em></figcaption></figure><h3>1. Understanding Phishing Attacks</h3><p>Phishing is a form of social engineering in which attackers manipulate people into performing actions that may compromise their security.</p><p>Rather than directly attacking a computer system, phishing often targets human behaviour.</p><p>Some common phishing techniques include:</p><p><strong>Email Spoofing:</strong> Attackers make messages appear to come from trusted organizations or individuals.</p><p><strong>Fake Login Pages:</strong> Victims are redirected to websites that imitate legitimate login pages.</p><p><strong>Urgent Account Warnings:</strong> Messages create pressure by claiming that an account will be blocked or suspended.</p><p><strong>Financial Scams:</strong> Fake payment requests or refund messages attempt to steal financial information.</p><p><strong>Malicious Attachments:</strong> Emails encourage users to open files that may contain harmful software.</p><p>The language used in these messages can contain useful clues, including suspicious requests, unusual urgency, and requests for sensitive information.</p><p>These patterns make email text a useful starting point for a Machine Learning classification experiment.</p><h3>2. Why Use Artificial Intelligence for Email Security?</h3><p>Traditional email filtering systems often use predefined rules, blocked sender lists, and known spam patterns.</p><p>These methods are useful, but attackers can modify their messages to avoid simple detection rules.</p><p>Machine Learning approaches the problem differently.</p><p>Instead of depending entirely on manually written rules, a classification model learns patterns from labelled examples.</p><p>For example, a model may learn that certain combinations of words, phrases, and message structures are associated with phishing messages in its training dataset.</p><p>When a new email is supplied, the model converts its text into numerical features and predicts the category.</p><p>AI-based email classification can support security analysis by:</p><ul><li>Identifying suspicious language patterns.</li><li>Processing large numbers of text messages.</li><li>Applying consistent classification rules learned from training data.</li><li>Supporting automated email-review workflows.</li><li>Helping security teams prioritize messages for further inspection.</li></ul><p>However, a text classifier cannot guarantee that an email is safe or malicious. Real-world email security requires additional information such as sender authentication, URL reputation, attachment analysis, and security policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*oGkx0exfwr7fM-ROFmcqTg.png" /><figcaption><em>Figure 2. An AI-based workflow for analyzing incoming email messages.</em></figcaption></figure><h3>3. How Does the Detection System Work?</h3><p>Our proposed system follows a simple Machine Learning workflow.</p><p><strong>Stage 1 — Email Input:</strong> The user provides the email subject or message content.</p><p><strong>Stage 2 — Text Preprocessing:</strong> The message is converted into a consistent text representation.</p><p><strong>Stage 3 — Feature Extraction:</strong> TF-IDF converts words and phrases into numerical features.</p><p><strong>Stage 4 — Model Classification:</strong> A trained Logistic Regression model analyzes the extracted features.</p><p><strong>Stage 5 — Prediction:</strong> The system predicts whether the message resembles phishing or legitimate examples.</p><p><strong>Stage 6 — Result Display:</strong> The application displays the predicted category and estimated model probability.</p><p>This process allows an ordinary text message to be processed by a Machine Learning algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*eJdlZSpzrtsslE7mmtMFFA.png" /><figcaption><em>Figure 3. An email message being examined for suspicious language and patterns.</em></figcaption></figure><h3>4. Understanding the Dataset</h3><p>Machine Learning requires examples from which a model can learn.</p><p>For this project, each email message is associated with a label.</p><p>We use two categories:</p><p><strong>Phishing:</strong> Messages labelled as suspicious or fraudulent.</p><p><strong>Legitimate:</strong> Messages labelled as normal communication.</p><p>A simplified dataset might look like this:</p><p>Email messageLabelVerify your account immediately using this linkPhishingYour account has been selected for a special rewardPhishingYour monthly electricity bill is now availableLegitimateThe meeting has been moved to 3 PMLegitimateYour password expires today, confirm your loginPhishing</p><p>These are illustrative examples rather than records from a real email collection.</p><p>For a beginner-friendly demonstration, we will create a small sample dataset directly in Python. A production-quality model would require a much larger, representative, properly labelled email dataset.</p><h3>5. Understanding the Technologies</h3><h3>Natural Language Processing (NLP)</h3><p>Natural Language Processing is a field of Artificial Intelligence that enables computers to process and analyze human language.</p><p>In this project, NLP techniques help transform email messages into a format that a Machine Learning model can understand.</p><h3>TF-IDF: Converting Text into Numerical Features</h3><p>Machine Learning algorithms generally require numerical input.</p><p>TF-IDF stands for Term Frequency–Inverse Document Frequency.</p><p>It represents words according to their importance within a document and across a collection of documents.</p><p>In simple terms:</p><ul><li>Term Frequency measures how often a word appears in a message.</li><li>Inverse Document Frequency reduces the importance of words that appear frequently across many messages.</li><li>The resulting values form numerical features for the classification model.</li></ul><p>These features help the algorithm identify patterns in email content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*iZ32HgMkd9rpE2_8m1x2hw.png" /><figcaption><em>Figure 4. Converting email text into numerical features using TF-IDF.</em></figcaption></figure><h3>Logistic Regression: Classifying Email Messages</h3><p>Logistic Regression is a Machine Learning algorithm used for classification.</p><p>Although its name contains the word regression, it is commonly used to predict categories.</p><p>In our project, it learns relationships between the TF-IDF features and the email labels.</p><p>When a new message is supplied, the model estimates the probability of each class and produces a classification.</p><p>We select Logistic Regression because it is relatively simple, efficient, and suitable for a beginner-level text-classification experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*3qxmwNIpv8mNZaOX_tf1PA.png" /><figcaption><em>Figure 5. The classification process using TF-IDF features and Logistic Regression.</em></figcaption></figure><h3>6. Technology Stack</h3><p>The project uses the following technologies:</p><p><strong>Python:</strong> Main programming language.</p><p><strong>Pandas:</strong> Organizes the sample email dataset.</p><p><strong>Scikit-learn:</strong> Provides TF-IDF, Logistic Regression, train-test splitting, and evaluation tools.</p><p><strong>Streamlit:</strong> Creates an interactive web application.</p><p><strong>NumPy:</strong> Supports numerical operations.</p><h3>7. Practical Implementation: Building the Phishing Detector</h3><p>Now let’s implement the project step by step.</p><h3>Step 1 — Install the Required Libraries</h3><p>Open the VS Code terminal and run:</p><pre>py -m pip install streamlit pandas scikit-learn</pre><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named AI_Phishing_Email_Detector.</p><p>Inside the folder, create the following files:</p><pre>AI_Phishing_Email_Detector/<br>│<br>├── app.py<br>└── requirements.txt</pre><p>Add these libraries to requirements.txt:</p><pre>streamlit<br>pandas<br>scikit-learn</pre><h3>Step 3 — Create the Sample Dataset</h3><p>Create a Python file named app.py.</p><p>First, import the required libraries and prepare the sample dataset.</p><pre>import streamlit as st<br>import pandas as pd</pre><pre>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.pipeline import Pipeline<br>from sklearn.metrics import accuracy_score, classification_report</pre><pre># Sample email dataset<br>data = {<br>    &quot;email&quot;: [<br>        &quot;Your bank account is suspended verify your password now&quot;,<br>        &quot;Congratulations you won a free prize click this link&quot;,<br>        &quot;Urgent update your account details immediately&quot;,<br>        &quot;Your payment failed confirm your card information&quot;,<br>        &quot;You have received a reward claim it today&quot;,<br>        &quot;Click here to verify your account and avoid suspension&quot;,<br>        &quot;Your account will be blocked unless you login now&quot;,<br>        &quot;We detected unusual activity verify your identity&quot;,<br>        &quot;Claim your cash reward by clicking the link&quot;,<br>        &quot;Your password expires today confirm your details&quot;,<br>        &quot;Your electricity bill is ready for download&quot;,<br>        &quot;The meeting is scheduled for tomorrow morning&quot;,<br>        &quot;Thank you for attending our training session&quot;,<br>        &quot;Your monthly subscription payment was successful&quot;,<br>        &quot;Please review the attached project report&quot;,<br>        &quot;The college examination timetable is available&quot;,<br>        &quot;Your order has been shipped successfully&quot;,<br>        &quot;The team meeting starts at three in the afternoon&quot;,<br>        &quot;Your appointment is confirmed for Monday&quot;,<br>        &quot;Please submit your assignment before the deadline&quot;<br>    ],</pre><pre>    &quot;label&quot;: [<br>        &quot;Phishing&quot;, &quot;Phishing&quot;, &quot;Phishing&quot;, &quot;Phishing&quot;,<br>        &quot;Phishing&quot;, &quot;Phishing&quot;, &quot;Phishing&quot;, &quot;Phishing&quot;,<br>        &quot;Phishing&quot;, &quot;Phishing&quot;,<br>        &quot;Legitimate&quot;, &quot;Legitimate&quot;, &quot;Legitimate&quot;,<br>        &quot;Legitimate&quot;, &quot;Legitimate&quot;, &quot;Legitimate&quot;,<br>        &quot;Legitimate&quot;, &quot;Legitimate&quot;, &quot;Legitimate&quot;,<br>        &quot;Legitimate&quot;<br>    ]<br>}</pre><pre>df = pd.DataFrame(data)</pre><pre>st.title(&quot;AI-Powered Phishing Email Detector&quot;)</pre><pre>st.write(&quot;Sample email dataset&quot;)</pre><pre>st.dataframe(df.head(10))</pre><h3>Understanding the Dataset Code</h3><p>The program imports Streamlit and Pandas.</p><p>A dictionary stores sample email messages and their corresponding labels.</p><p>Each email is classified as either Phishing or Legitimate.</p><p>The pd.DataFrame() function converts the dictionary into a structured dataset.</p><p>Streamlit displays the first ten records in a table.</p><h3>Step 4 — Convert Email Text into Numerical Features</h3><p>Add the following code below the dataset section.</p><pre># Separate input text and target labels<br>X = df[&quot;email&quot;]<br>y = df[&quot;label&quot;]</pre><pre># Split data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.25,<br>    random_state=42,<br>    stratify=y<br>)</pre><pre># Create TF-IDF and Logistic Regression pipeline<br>model = Pipeline([<br>    (<br>        &quot;tfidf&quot;,<br>        TfidfVectorizer(<br>            lowercase=True,<br>            stop_words=&quot;english&quot;,<br>            ngram_range=(1, 2)<br>        )<br>    ),</pre><pre>    (<br>        &quot;classifier&quot;,<br>        LogisticRegression(max_iter=1000)<br>    )<br>])</pre><pre># Train the model<br>model.fit(X_train, y_train)</pre><pre># Predict test data<br>predictions = model.predict(X_test)</pre><pre># Calculate accuracy<br>accuracy = accuracy_score(<br>    y_test,<br>    predictions<br>)</pre><pre>print(&quot;Model Training Completed!&quot;)</pre><pre>print(<br>    &quot;Accuracy:&quot;,<br>    round(accuracy * 100, 2),<br>    &quot;%&quot;<br>)</pre><pre>print(&quot;\nClassification Report:&quot;)</pre><pre>print(<br>    classification_report(<br>        y_test,<br>        predictions,<br>        zero_division=0<br>    )<br>)</pre><h3>Understanding the Training Process</h3><p>The program separates the email messages from their labels.</p><p>The train_test_split() function divides the dataset into training and testing portions.</p><p>The TfidfVectorizer() converts text into numerical features.</p><p>The ngram_range=(1, 2) setting allows the model to consider individual words and pairs of consecutive words.</p><p>The Pipeline() connects TF-IDF and Logistic Regression into one workflow.</p><p>The model learns from the training data and generates predictions for the testing data.</p><p>Finally, accuracy and classification metrics are calculated.</p><h3>Step 5 — Build the Interactive Email Detection Application</h3><p>Add the following code at the bottom of app.py.</p><pre>st.subheader(&quot;Analyze an Email&quot;)</pre><pre>email_text = st.text_area(<br>    &quot;Paste an email message below:&quot;,<br>    placeholder=&quot;Enter the email content here...&quot;<br>)</pre><pre>if st.button(&quot;Analyze Email&quot;):</pre><pre>    if email_text.strip() == &quot;&quot;:<br>        st.warning(&quot;Please enter an email message.&quot;)</pre><pre>    else:<br>        prediction = model.predict([email_text])[0]</pre><pre>        probabilities = model.predict_proba(<br>            [email_text]<br>        )[0]</pre><pre>        classes = model.named_steps[<br>            &quot;classifier&quot;<br>        ].classes_</pre><pre>        st.subheader(&quot;Detection Result&quot;)</pre><pre>        if prediction == &quot;Phishing&quot;:</pre><pre>            st.error(<br>                &quot;Potential Phishing Email Detected!&quot;<br>            )</pre><pre>        else:</pre><pre>            st.success(<br>                &quot;Classified as Legitimate&quot;<br>            )</pre><pre>        st.write(<br>            &quot;Predicted Category:&quot;,<br>            prediction<br>        )</pre><pre>        probability_data = pd.DataFrame({<br>            &quot;Category&quot;: classes,<br>            &quot;Estimated Probability&quot;: probabilities<br>        })</pre><pre>        st.write(&quot;Model Probability Estimates&quot;)</pre><pre>        st.dataframe(probability_data)</pre><pre>        st.caption(<br>            &quot;This is an educational prototype. &quot;<br>            &quot;A legitimate classification does not &quot;<br>            &quot;guarantee that an email is safe.&quot;<br>        )</pre><pre>st.divider()</pre><pre>st.subheader(&quot;Model Evaluation&quot;)</pre><pre>st.metric(<br>    &quot;Test Accuracy&quot;,<br>    f&quot;{accuracy * 100:.2f}%&quot;<br>)</pre><h3>Understanding the Application</h3><p>The st.text_area() function provides an input area where users can paste an email message.</p><p>When the user clicks the Analyze Email button, the system checks whether the input is empty.</p><p>The trained model then predicts the category of the message.</p><p>The application displays the classification result and the model’s estimated probabilities.</p><p>Finally, the model’s test accuracy is displayed.</p><p>This creates a simple interface through which users can experiment with email classification.</p><h3>8. Running the Project</h3><p>Open the VS Code terminal inside the project folder.</p><p>Run:</p><pre>py -m streamlit run app.py</pre><p>The application will open in your browser.</p><p>Paste a sample email message into the text area and click <strong>Analyze Email</strong>.</p><p>The application will display the predicted category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Lr9M1T9cy-sIRLpT8Ws2NA.png" /><figcaption><em>Figure 6. Illustrative model evaluation dashboard.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*VvQBRALyD0CoA9fQmx2Fdw.png" /><figcaption><em>Figure 7. Conceptual interface for the email detection application. Replace this illustration with a screenshot of your running application.</em></figcaption></figure><h3>9. Understanding the Results</h3><p>Consider the following example:</p><p><strong>Input Email:</strong></p><p>“Your bank account will be suspended. Verify your password immediately by clicking this link.”</p><p>The system processes the message using the trained TF-IDF and Logistic Regression pipeline.</p><p>An illustrative expected result is:</p><p><strong>Predicted Category: Phishing</strong></p><p>Now consider another message:</p><p><strong>Input Email:</strong></p><p>“Your college examination timetable is available. Please check the student portal.”</p><p>The system may classify it as:</p><p><strong>Predicted Category: Legitimate</strong></p><p>These examples demonstrate how the model uses patterns learned from the sample training messages.</p><p>The exact result depends on the trained model and input text.</p><p>Because the demonstration dataset is very small and manually created, its predictions and evaluation accuracy should not be treated as evidence of real-world phishing detection performance.</p><h3>10. Model Evaluation</h3><p>Evaluating a Machine Learning model is essential to understanding its performance.</p><p>This project uses the following metrics:</p><p><strong>Accuracy:</strong> Measures the percentage of correctly classified test records.</p><p><strong>Precision:</strong> Measures how many emails predicted as phishing actually belong to the phishing category.</p><p><strong>Recall:</strong> Measures how many actual phishing examples the model successfully identifies.</p><p><strong>F1-Score:</strong> Combines precision and recall.</p><p><strong>Classification Report:</strong> Displays precision, recall, F1-score, and support for each class.</p><p>For phishing detection, recall is especially important because failing to identify a phishing email can expose users to security risks.</p><p>However, precision also matters because incorrectly flagging legitimate emails can disrupt normal communication.</p><p>A reliable system needs a larger and more representative dataset, independent testing, and continuous evaluation.</p><h3>11. Advantages of the Proposed System</h3><p><strong>Automated Classification:</strong> The model can classify email text without manually reviewing every message.</p><p><strong>Fast Processing:</strong> Text classification can be performed quickly after the model has been trained.</p><p><strong>Pattern Recognition:</strong> Machine Learning can identify combinations of words and phrases associated with training examples.</p><p><strong>Interactive Interface:</strong> Streamlit makes the project easy to demonstrate.</p><p><strong>Expandable Architecture:</strong> Additional features such as URL analysis, sender reputation, and attachment inspection can be integrated.</p><p><strong>Educational Value:</strong> The project demonstrates the practical connection between NLP and Machine Learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*HhePLW0GjL3w-UslldQTNg.png" /><figcaption><em>Figure 8. Phishing threats and the importance of layered email security.</em></figcaption></figure><h3>12. Challenges and Limitations</h3><p>Although the system demonstrates an interesting application of AI, it has several limitations.</p><p><strong>Small Dataset:</strong> The sample dataset contains only a limited number of manually created messages.</p><p><strong>Changing Attack Patterns:</strong> Attackers frequently change their language and techniques.</p><p><strong>Context Understanding:</strong> TF-IDF does not fully understand the meaning or intention behind an email.</p><p><strong>False Positives:</strong> Legitimate emails may be incorrectly classified as phishing.</p><p><strong>False Negatives:</strong> Some phishing messages may be classified as legitimate.</p><p><strong>Missing Email Metadata:</strong> The current model analyzes text only. It does not inspect sender domains, URLs, attachments, or authentication information.</p><p><strong>Dataset Bias:</strong> A model may learn patterns specific to its training examples instead of general phishing characteristics.</p><p>These limitations show why a text-based classifier should be considered one component of a larger email security system.</p><h3>13. Future Scope: Towards Smarter Email Security</h3><p>The current project can be extended into a more advanced security application.</p><p><strong>Larger Email Datasets:</strong> Train and evaluate the model using publicly available, appropriately labelled email datasets.</p><p><strong>Advanced NLP Models:</strong> Explore transformer-based language models for more sophisticated text analysis.</p><p><strong>URL Analysis:</strong> Examine suspicious links using trusted URL reputation services.</p><p><strong>Sender Verification:</strong> Include sender-domain information and email authentication signals.</p><p><strong>Attachment Analysis:</strong> Integrate safe file-analysis mechanisms to examine suspicious attachments.</p><p><strong>Real-Time Email Integration:</strong> Explore integration with supported email services and security workflows.</p><p><strong>Explainable AI:</strong> Provide understandable reasons for why a message was flagged, rather than displaying only a category.</p><p>These improvements could help transform a basic classification prototype into a more comprehensive email security solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*TorhsekqcYLvt_-jenH4Aw.png" /><figcaption><em>Figure 9. A vision of intelligent email security combining AI analysis and human oversight.</em></figcaption></figure><h3>Conclusion: Making Email Communication Safer with AI</h3><p>Phishing remains a significant cybersecurity challenge because attackers exploit both technology and human behaviour.</p><p>Artificial Intelligence offers useful techniques for analyzing email content and identifying patterns associated with suspicious messages.</p><p>In this project, we explored how Natural Language Processing, TF-IDF, and Logistic Regression can be combined to create a basic phishing email classification system.</p><p>By using Python, Scikit-learn, and Streamlit, we demonstrated the complete workflow from preparing sample data to training a model and building an interactive application.</p><p>The experiment also highlights an important lesson: a Machine Learning prediction is not a guarantee of security.</p><p>Real-world phishing detection requires larger datasets, multiple security signals, continuous evaluation, and human awareness.</p><p><strong>The future of email security is not simply about blocking suspicious messages. It is about combining intelligent analysis, reliable security practices, and informed human decisions.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6488537596da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smarter Retrieval: Improving RAG Accuracy with Reranking Techniques]]></title>
            <link>https://medium.com/@reddykowshik2008/smarter-retrieval-improving-rag-accuracy-with-reranking-techniques-e9a5cf26389b?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9a5cf26389b</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 17:40:12 GMT</pubDate>
            <atom:updated>2026-12-01T17:40:12.970Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why finding the right information is only half the problem — and how reranking helps AI applications retrieve more relevant knowledge.</em></p><h3>Introduction: When Finding Information Is Not Enough</h3><p>Imagine asking an intelligent assistant:</p><p>“What are the eligibility requirements for a university scholarship?”</p><p>The system searches its document collection and retrieves five paragraphs. Some contain information about scholarships, while others discuss general admission rules, fee payments, or unrelated financial support.</p><p>The problem is not that the system cannot find information. The problem is that it does not always find the <strong>most relevant information first</strong>.</p><p>This is one of the important challenges in Retrieval-Augmented Generation (RAG).</p><p>RAG allows an AI application to retrieve information from external documents and use that information when generating responses. However, the quality of the final answer depends heavily on the quality of the retrieved context.</p><p>A system may have access to thousands of useful documents, but if it retrieves irrelevant passages, the generated response may also become incomplete or inaccurate.</p><p>This leads to an important question:</p><p><strong>How can we improve the relevance of retrieved information before passing it to an AI model?</strong></p><p>One promising approach is called <strong>Reranking</strong>.</p><p>In this article, we explore how reranking works, why it matters in RAG applications, and how to build a practical retrieval and reranking system using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RksLUfku2EyZvKm5N4dZjw.png" /><figcaption><em>A visual introduction to retrieval and reranking in modern RAG systems.</em></figcaption></figure><h3>1. Understanding Retrieval-Augmented Generation</h3><p>Retrieval-Augmented Generation combines information retrieval with language generation.</p><p>Instead of depending only on information learned during model training, a RAG application can search an external knowledge source and provide relevant content as context.</p><p>For example, consider a university chatbot that answers questions using academic regulations, examination guidelines, and student handbooks.</p><p>When a student asks a question, the application:</p><ol><li>Receives the user’s question.</li><li>Searches the available documents.</li><li>Retrieves potentially relevant passages.</li><li>Provides the retrieved information as context.</li><li>Generates a response using that context.</li></ol><p>This architecture helps applications work with specific or updated information that may not be available in a model’s original training data.</p><p>However, retrieval introduces another challenge: the first search results are not always the most useful results.</p><h3>2. The Problem with Traditional Retrieval</h3><p>A retrieval system searches a document collection and returns passages that appear relevant to a query.</p><p>Traditional keyword-based retrieval often focuses on matching words between the query and documents.</p><p>Consider this question:</p><p>“How can students apply for financial assistance?”</p><p>A document collection might contain the following passages:</p><ul><li>Document A: “Students can submit a financial assistance application through the university portal.”</li><li>Document B: “Financial management is an important skill for business students.”</li><li>Document C: “Students must complete the scholarship application before the deadline.”</li><li>Document D: “The university provides online resources for student registration.”</li></ul><p>All four passages contain words that may appear related to the question. However, some are more useful than others.</p><p>A keyword-based system may retrieve passages based on word overlap without fully understanding their relevance to the user’s intention.</p><p>This can create three problems:</p><p><strong>Irrelevant Results:</strong> Documents containing similar words may not answer the actual question.</p><p><strong>Missing Context:</strong> Important information may appear lower in the result list.</p><p><strong>Poor Answer Quality:</strong> If irrelevant passages are passed to a language model, they may reduce the usefulness of the generated response.</p><p>The solution is not necessarily to retrieve more documents. It is to improve the ranking of the documents already retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*qi404Rx9sQWms9Egosln_Q.png" /><figcaption><em>Why retrieving documents is not enough — relevance matters.</em></figcaption></figure><h3>3. What Is Reranking?</h3><p>Reranking is a second-stage process that evaluates retrieved documents again and changes their order according to their relevance to the original query.</p><p>It works after the initial retrieval stage.</p><p>The process has two main components:</p><p><strong>First Stage — Retriever</strong></p><p>A fast retrieval method searches a large collection and selects a smaller group of potentially relevant documents.</p><p><strong>Second Stage — Reranker</strong></p><p>A more detailed model examines the query and each retrieved document together. It calculates relevance scores and rearranges the documents.</p><p>For example:</p><p>DocumentInitial rankReranked positionDocument A31Document B14Document C22Document D43</p><p>This is an illustrative ranking, not a measured experiment.</p><p>The important idea is that the reranker can move a highly relevant document higher, even if the first retrieval method placed it lower.</p><p>According to the Sentence Transformers documentation, a retrieve-and-rerank pipeline uses an efficient first-stage retriever followed by a Cross-Encoder that scores the query-document pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*APn2rrRjpPDarF-Xi6KWug.png" /><figcaption><em>The two-stage process: retrieve candidate documents first, then rerank them.</em></figcaption></figure><h3>4. Understanding the Two Main Components</h3><h3>4.1 Retriever: Finding Candidate Documents</h3><p>The retriever is responsible for quickly searching the document collection.</p><p>There are different ways to perform retrieval:</p><p><strong>Keyword-Based Retrieval:</strong> Finds documents using matching terms and word frequencies.</p><p><strong>Dense Retrieval:</strong> Converts queries and documents into numerical embeddings and compares their semantic similarity.</p><p><strong>Hybrid Retrieval:</strong> Combines keyword-based and semantic retrieval approaches.</p><p>For our practical demonstration, we will use TF-IDF with cosine similarity.</p><p>TF-IDF represents documents using numerical word features. Cosine similarity compares the query representation with each document representation.</p><p>This provides a simple first-stage retrieval method.</p><h3>4.2 Reranker: Understanding Relevance More Deeply</h3><p>A reranker evaluates each candidate document against the original query.</p><p>We will use a Cross-Encoder model.</p><p>Unlike a bi-encoder, which creates independent embeddings for queries and documents, a Cross-Encoder processes both inputs together and produces a relevance score.</p><p>This allows the model to examine relationships between the query and document more directly.</p><p>Cross-Encoders are generally more computationally expensive than bi-encoders, so they are commonly applied only to a smaller set of retrieved candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ncbhonBuSgvQdoDLIQb8pA.png" /><figcaption><em>Comparing how bi-encoders and Cross-Encoders process queries and documents.</em></figcaption></figure><h3>5. Understanding the Architecture</h3><p>Our project follows a two-stage retrieval architecture.</p><p><strong>User Query:</strong> The user enters a question.</p><p><strong>Document Collection:</strong> The system stores a set of text passages.</p><p><strong>TF-IDF Retriever:</strong> The query is compared with the document collection using cosine similarity.</p><p><strong>Candidate Selection:</strong> The most similar passages are selected.</p><p><strong>Cross-Encoder Reranker:</strong> The query and candidate passages are evaluated together.</p><p><strong>Final Ranking:</strong> The passages are sorted according to their reranking scores.</p><p><strong>Results Display:</strong> The application displays the initial and reranked results.</p><p>The architecture is designed to improve the ordering of retrieved passages before they are used by a downstream RAG application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*4BydyT643DFBKc3h5InR3g.png" /><figcaption><em>Overall architecture of the proposed retrieval and reranking system.</em></figcaption></figure><h3>6. Technologies Used</h3><p>The project uses the following technologies:</p><p><strong>Python:</strong> Main programming language.</p><p><strong>Scikit-learn:</strong> Provides TF-IDF vectorization and cosine similarity.</p><p><strong>Sentence Transformers:</strong> Provides pretrained Cross-Encoder models for reranking.</p><p><strong>Streamlit:</strong> Creates the interactive application.</p><p><strong>Pandas:</strong> Organizes and displays retrieved results.</p><h3>7. Practical Implementation: Building a Retrieval and Reranking System</h3><p>Now let’s build a working prototype.</p><p>Our demonstration will use a small collection of university-related documents. Users can enter a question and compare the initial retrieval order with the reranked order.</p><h3>Step 1 — Install the Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install streamlit sentence-transformers scikit-learn pandas</pre><p>The Sentence Transformers library will download the selected pretrained model the first time it is loaded.</p><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named RAG_Reranking_System.</p><p>Inside the folder, create these files:</p><pre>RAG_Reranking_System/<br>│<br>├── app.py<br>└── requirements.txt</pre><p>Add the following libraries to requirements.txt:</p><pre>streamlit<br>sentence-transformers<br>scikit-learn<br>pandas</pre><h3>Step 3 — Prepare the Document Collection</h3><p>Create a small collection of sample documents.</p><pre>documents = [<br>    &quot;Students can apply for scholarships through the university portal. Applications must be submitted before the announced deadline.&quot;,</pre><pre>    &quot;The examination department publishes semester examination timetables on the student portal.&quot;,</pre><pre>    &quot;Students requesting financial assistance must submit an application with the required supporting documents.&quot;,</pre><pre>    &quot;The library provides access to academic books, research journals, and digital learning resources.&quot;,</pre><pre>    &quot;Scholarship eligibility depends on academic performance, family income, and the specific scholarship requirements.&quot;,</pre><pre>    &quot;Students can pay their semester fees through the university&#39;s online payment portal.&quot;,</pre><pre>    &quot;The admission office provides information about undergraduate and postgraduate admission procedures.&quot;,</pre><pre>    &quot;Students must register for courses before the semester registration deadline.&quot;,</pre><pre>    &quot;Financial assistance applications are reviewed by the university committee after document verification.&quot;,</pre><pre>    &quot;The university organizes technical workshops, seminars, and professional development programs.&quot;<br>]</pre><p>Each entry represents a short document passage.</p><p>For this demonstration, the documents are written manually. A real RAG application would usually obtain passages from PDFs, websites, databases, or other knowledge sources.</p><h3>Step 4 — Implement the Initial Retriever</h3><p>We will use TF-IDF and cosine similarity to identify candidate documents.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics.pairwise import cosine_similarity</pre><pre># Create the TF-IDF vectorizer<br>vectorizer = TfidfVectorizer(stop_words=&quot;english&quot;)</pre><pre># Convert documents into numerical vectors<br>document_vectors = vectorizer.fit_transform(documents)</pre><pre>def retrieve_documents(query, top_k=5):</pre><pre>    # Convert the user query into a vector<br>    query_vector = vectorizer.transform([query])</pre><pre>    # Calculate cosine similarity<br>    scores = cosine_similarity(<br>        query_vector,<br>        document_vectors<br>    ).flatten()</pre><pre>    # Get the highest-scoring document positions<br>    ranked_indices = scores.argsort()[::-1][:top_k]</pre><pre>    results = []</pre><pre>    for index in ranked_indices:<br>        results.append({<br>            &quot;document&quot;: documents[index],<br>            &quot;score&quot;: float(scores[index])<br>        })</pre><pre>    return results</pre><h3>Understanding the Retriever Code</h3><p>The TfidfVectorizer() converts text documents into numerical feature vectors.</p><p>The fit_transform() function learns the vocabulary and creates document vectors.</p><p>When a user enters a query, transform() converts the query using the same vocabulary.</p><p>The cosine_similarity() function compares the query vector with all document vectors.</p><p>Finally, argsort() helps identify the documents with the highest similarity scores.</p><p>These documents become the candidates for the next stage.</p><h3>Step 5 — Load the Cross-Encoder Reranker</h3><p>Now we introduce the main component of our project.</p><pre>from sentence_transformers import CrossEncoder</pre><pre># Load a pretrained reranking model<br>reranker = CrossEncoder(<br>    &quot;cross-encoder/ms-marco-MiniLM-L6-v2&quot;<br>)</pre><p>The selected model is a pretrained Cross-Encoder designed for passage-ranking tasks.</p><p>The first time this code runs, the model needs to be downloaded. An internet connection is therefore required during the initial download unless the model is already cached locally.</p><h3>Step 6 — Implement the Reranking Function</h3><p>The following function evaluates each retrieved document against the user’s original question.</p><pre>def rerank_documents(query, retrieved_documents):</pre><pre>    # Prepare query-document pairs<br>    pairs = [<br>        [query, item[&quot;document&quot;]]<br>        for item in retrieved_documents<br>    ]</pre><pre>    # Calculate relevance scores<br>    scores = reranker.predict(pairs)</pre><pre>    # Attach reranking scores<br>    reranked_results = []</pre><pre>    for item, score in zip(retrieved_documents, scores):</pre><pre>        reranked_results.append({<br>            &quot;document&quot;: item[&quot;document&quot;],<br>            &quot;score&quot;: float(score)<br>        })</pre><pre>    # Sort by reranking score<br>    reranked_results.sort(<br>        key=lambda x: x[&quot;score&quot;],<br>        reverse=True<br>    )</pre><pre>    return reranked_results</pre><h3>Understanding the Reranking Function</h3><p>The function receives the original query and the candidate documents.</p><p>The pairs list combines the query with each candidate passage.</p><p>The reranker.predict() method evaluates these query-document pairs and returns relevance scores.</p><p>The program attaches each score to its corresponding document.</p><p>Finally, sort() arranges the results in descending score order.</p><p>An important detail: these scores are ranking signals, not guaranteed probabilities. A higher score means the model ranks that passage as more relevant relative to the other candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PjVNVGYysZBMAExSOR61Cg.png" /><figcaption><em>A Cross-Encoder evaluates query-document pairs and assigns relevance scores.</em></figcaption></figure><h3>Step 7 — Build the Streamlit Application</h3><p>Now we create an interactive interface to compare both retrieval stages.</p><pre>import streamlit as st<br>import pandas as pd</pre><pre>st.set_page_config(<br>    page_title=&quot;RAG Reranking Playground&quot;,<br>    page_icon=&quot;🔎&quot;,<br>    layout=&quot;wide&quot;<br>)</pre><pre>st.title(&quot;🔎 RAG Retrieval and Reranking Playground&quot;)</pre><pre>st.write(<br>    &quot;Explore how reranking changes the order &quot;<br>    &quot;of retrieved documents.&quot;<br>)</pre><pre>query = st.text_input(<br>    &quot;Enter your question:&quot;,<br>    placeholder=&quot;How can students apply for financial assistance?&quot;<br>)</pre><pre>top_k = st.slider(<br>    &quot;Number of candidate documents&quot;,<br>    min_value=2,<br>    max_value=len(documents),<br>    value=5<br>)</pre><pre>if st.button(&quot;Search and Rerank&quot;):</pre><pre>    if query.strip():</pre><pre>        with st.spinner(&quot;Retrieving candidate documents...&quot;):</pre><pre>            initial_results = retrieve_documents(<br>                query,<br>                top_k<br>            )</pre><pre>        with st.spinner(&quot;Reranking documents...&quot;):</pre><pre>            final_results = rerank_documents(<br>                query,<br>                initial_results<br>            )</pre><pre>        st.success(&quot;Retrieval and reranking completed!&quot;)</pre><pre>        col1, col2 = st.columns(2)</pre><pre>        with col1:</pre><pre>            st.subheader(&quot;Initial Retrieval&quot;)</pre><pre>            for i, item in enumerate(initial_results):</pre><pre>                st.write(f&quot;**Rank {i + 1}**&quot;)</pre><pre>                st.write(item[&quot;document&quot;])</pre><pre>                st.caption(<br>                    f&quot;TF-IDF similarity: {item[&#39;score&#39;]:.4f}&quot;<br>                )</pre><pre>                st.divider()</pre><pre>        with col2:</pre><pre>            st.subheader(&quot;After Reranking&quot;)</pre><pre>            for i, item in enumerate(final_results):</pre><pre>                st.write(f&quot;**Rank {i + 1}**&quot;)</pre><pre>                st.write(item[&quot;document&quot;])</pre><pre>                st.caption(<br>                    f&quot;Cross-Encoder score: {item[&#39;score&#39;]:.4f}&quot;<br>                )</pre><pre>                st.divider()</pre><pre>        comparison = pd.DataFrame({<br>            &quot;Initial Retrieval&quot;: [<br>                item[&quot;document&quot;]<br>                for item in initial_results<br>            ],<br>            &quot;Reranked Results&quot;: [<br>                item[&quot;document&quot;]<br>                for item in final_results<br>            ]<br>        })</pre><pre>        st.subheader(&quot;Result Comparison&quot;)</pre><pre>        st.dataframe(<br>            comparison,<br>            use_container_width=True<br>        )</pre><pre>    else:</pre><pre>        st.warning(&quot;Please enter a question.&quot;)</pre><h3>Step 8 — Run the Application</h3><p>Open the terminal inside the project folder and run:</p><pre>py -m streamlit run app.py</pre><p>The application will open in your browser.</p><p>Enter a question such as:</p><p>“How can students apply for financial assistance?”</p><p>Click <strong>Search and Rerank</strong>.</p><p>The application displays the initial retrieval results and the new order produced by the Cross-Encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*jmPuWLbD_aqIGHw5ghkCUQ.png" /><figcaption><em>The interactive interface for exploring retrieval and reranking. Ideally, replace this illustration with a screenshot of your actual running application.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ciJCultBO4WhNSX1vXxwgQ.png" /><figcaption><em>Comparing the initial retrieval ranking with the reranked document order. Replace with actual application output if available.</em></figcaption></figure><h3>8. Understanding the Results</h3><p>The system produces two result lists.</p><p>The first list shows the documents selected by TF-IDF retrieval.</p><p>The second list shows the same candidate documents after Cross-Encoder reranking.</p><p>For example, a question about scholarship eligibility may retrieve passages about scholarship applications, financial assistance, and general university procedures.</p><p>The reranker then evaluates the relationship between the question and each candidate passage.</p><p>A passage that directly explains eligibility may move above a passage that only discusses how to submit an application.</p><p>The exact ordering depends on the query, document collection, and model.</p><p><strong>Important:</strong> Reranking cannot recover a relevant document that the first-stage retriever never selected. It can only reorder the candidate documents it receives.</p><h3>9. Why Does Reranking Matter in RAG?</h3><p>Reranking can improve the relevance of the context supplied to a downstream language model.</p><p>Its main benefits include:</p><p><strong>Improved Relevance:</strong> Candidate documents are evaluated more closely against the original question.</p><p><strong>Better Context Selection:</strong> More relevant passages can be moved towards the top of the result list.</p><p><strong>Efficient Processing:</strong> The expensive reranking stage operates on a smaller candidate set instead of the entire document collection.</p><p><strong>Flexible Integration:</strong> Reranking can be added to existing keyword-based or semantic retrieval systems.</p><p><strong>Better Retrieval Control:</strong> Developers can compare the initial and final ranking to understand how the retrieval pipeline behaves.</p><p>However, improved ranking does not automatically guarantee that the final generated answer is correct. The quality of the documents and the generation process still matter.</p><h3>10. Challenges and Limitations</h3><p>Although reranking is useful, it introduces several engineering challenges.</p><p><strong>Additional Processing Time:</strong> Cross-Encoders evaluate query-document pairs individually, making reranking slower than simple similarity comparisons.</p><p><strong>Computational Requirements:</strong> Larger reranking models may require more memory and processing power.</p><p><strong>Candidate Selection:</strong> If the first-stage retriever misses an important passage, the reranker cannot bring it into the results.</p><p><strong>Document Quality:</strong> Incorrect, outdated, or incomplete documents can still produce poor results.</p><p><strong>Score Interpretation:</strong> Reranking scores should not automatically be treated as probabilities or universal relevance measurements.</p><p><strong>Scaling:</strong> Large document collections require careful selection of candidate counts, batch sizes, and model configurations.</p><p>A practical system must balance retrieval quality, speed, and computational cost.</p><h3>11. Future Scope: Building More Advanced Retrieval Systems</h3><p>The basic project can be expanded in several ways.</p><p><strong>Hybrid Retrieval:</strong> Combine keyword-based retrieval with dense semantic retrieval.</p><p><strong>Larger Document Collections:</strong> Integrate PDFs, academic materials, websites, and institutional databases.</p><p><strong>Advanced Rerankers:</strong> Experiment with different Cross-Encoder models and compare their ranking behaviour.</p><p><strong>Performance Evaluation:</strong> Use metrics such as Mean Reciprocal Rank (MRR), Normalized Discounted Cumulative Gain (NDCG), and Recall@K to evaluate retrieval quality.</p><p><strong>RAG Integration:</strong> Pass the top-ranked passages to a language model to generate answers based on retrieved context.</p><p><strong>Domain-Specific Retrieval:</strong> Develop specialized systems for universities, healthcare documentation, legal information, or technical support.</p><p>These improvements can make retrieval pipelines more useful for applications that depend on finding precise information from large document collections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ismgjyGX-E2ztiieo3KZtA.png" /><figcaption><em>The future of RAG — combining hybrid retrieval, reranking, and answer generation.</em></figcaption></figure><h3>Conclusion: Better Answers Begin with Better Retrieval</h3><p>Retrieval-Augmented Generation is not only about connecting a language model to a document collection. It is also about ensuring that the right information reaches the model at the right time.</p><p>Traditional retrieval methods provide an efficient way to identify candidate passages, but their initial ranking may not always reflect the user’s actual information need.</p><p>Reranking introduces a second evaluation stage that examines the relationship between a query and retrieved documents more closely.</p><p>In this project, we explored how TF-IDF retrieval and a Cross-Encoder can work together to build a two-stage retrieval system using Python.</p><p>The central lesson is simple:</p><p><strong>Finding information is important, but finding the most relevant information first is what makes a retrieval system more useful.</strong></p><p>As RAG applications continue to develop, retrieval optimization and reranking will remain important areas for building more reliable knowledge-based applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9a5cf26389b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch vs. Real-Time Machine Learning Inference: Choosing the Right Way to Make Predictions]]></title>
            <link>https://medium.com/@reddykowshik2008/batch-vs-real-time-machine-learning-inference-choosing-the-right-way-to-make-predictions-b890e6be9456?source=rss-ef562057d205------2</link>
            <guid isPermaLink="false">https://medium.com/p/b890e6be9456</guid>
            <dc:creator><![CDATA[Reddykowshik]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 17:39:54 GMT</pubDate>
            <atom:updated>2026-12-01T17:39:54.836Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding how machine learning models generate predictions, when to use batch processing, and how to build both approaches using Python.</em></p><h3>Introduction: Not Every Prediction Needs to Be Instant</h3><p>Imagine an online shopping company that uses machine learning to understand customer preferences.</p><p>Every day, thousands of customers visit its website. The company has two requirements:</p><ul><li>Recommend products immediately when a customer visits the website.</li><li>Analyze thousands of customer records every night to understand purchasing patterns.</li></ul><p>Should the company process every prediction immediately, or should it collect the data and process everything together?</p><p>These situations introduce two important approaches in machine learning deployment: <strong>Real-Time Inference</strong> and <strong>Batch Inference</strong>.</p><p>A machine learning model becomes useful when it can generate predictions at the right time and in the right way.</p><p>In this article, we will understand both approaches, compare their working principles, and build a practical Python application that supports single-record and batch predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR7OMVH_ShMSiNquwjrQCw.png" /></figure><h3>1. Understanding Machine Learning Inference</h3><p>Machine learning inference is the process of using a trained model to make predictions on new data.</p><p>During training, a model learns patterns from historical examples. During inference, it applies those learned patterns to previously unseen inputs.</p><p>For example, a model trained to classify flower species may use:</p><ul><li>Sepal length</li><li>Sepal width</li><li>Petal length</li><li>Petal width</li></ul><p>When a user provides measurements of a new flower, the model predicts its species.</p><p>This prediction process is called inference.</p><p>Inference is commonly used in product recommendations, fraud detection, spam classification, image recognition, and demand forecasting.</p><h3>2. What Is Real-Time Inference?</h3><p>Real-time inference generates a prediction when an application or user requests it.</p><p>The model receives an input, processes it, and returns a prediction without waiting for a scheduled batch.</p><p>For example, when a customer opens an online shopping application, the system can generate product recommendations based on the customer’s activity.</p><p>The process works as follows:</p><ol><li>A user sends a request.</li><li>The application receives the input.</li><li>The trained model processes the input.</li><li>The model generates a prediction.</li><li>The application returns the result.</li></ol><p><strong>Examples:</strong></p><ul><li>Spam detection when an email arrives.</li><li>Product recommendations while browsing.</li><li>Fraud detection during a transaction.</li><li>Classifying an incoming customer request.</li></ul><p>Real-time inference is useful when applications need quick responses. However, the system must handle incoming requests and manage response times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*EAL3pL2wAvQCRs80d4QIug.png" /></figure><h3>3. What Is Batch Inference?</h3><p>Batch inference generates predictions for a group of records together rather than processing each record immediately.</p><p>For example, an online shopping company may collect customer purchase information throughout the day.</p><p>Instead of generating every analytical prediction immediately, the company can process all collected records at night and store the results.</p><p>The process works as follows:</p><ol><li>Collect a group of input records.</li><li>Prepare the data for prediction.</li><li>Send the records to the trained model.</li><li>Generate predictions for the entire group.</li><li>Save the results.</li></ol><p><strong>Examples:</strong></p><ul><li>Predicting product demand for the next week.</li><li>Classifying thousands of customer records.</li><li>Generating daily sales forecasts.</li><li>Processing large collections of images.</li></ul><p>Batch inference is useful when immediate responses are not required and large amounts of data need to be processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*wov4aX-Em7c_WPCEPN8LTw.png" /></figure><h3>4. Batch Inference vs. Real-Time Inference</h3><p>Both approaches use trained machine learning models, but they differ in how and when predictions are generated.</p><p>FeatureBatch InferenceReal-Time InferenceProcessingMultiple records togetherIndividual requestsPrediction timeScheduled or on demandWhen request arrivesResponseUsually delayedQuick responseData handlingCollected recordsIncoming dataMain focusThroughputLow latencyCommon useReports and forecastingRecommendations and fraud checks</p><p>Google’s Machine Learning Crash Course discusses static and dynamic inference as different ways to serve predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ZTIqRMgMA6FMwc7qKz1qAQ.png" /></figure><h3>5. Understanding the System Architecture</h3><p>A machine learning inference system generally includes a trained model, input data, a prediction process, and an output destination.</p><p>A real-time system commonly exposes the model through an API. The client sends a request, the model generates a prediction, and the response is returned.</p><p>A batch system collects records from a file, database, or data pipeline. The records are processed together, and the predictions are saved.</p><p>Both approaches can use the same trained model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*khUfeSqRPbPtT_tTPThNxQ.png" /></figure><h3>6. Technologies Used in Our Practical Project</h3><p>We will use:</p><ul><li><strong>Python:</strong> Main programming language.</li><li><strong>Scikit-learn:</strong> Training the machine learning model.</li><li><strong>Pandas:</strong> Processing CSV records.</li><li><strong>Joblib:</strong> Saving and loading the trained model.</li><li><strong>FastAPI:</strong> Creating prediction API endpoints.</li><li><strong>Uvicorn:</strong> Running the API application.</li></ul><p>For our demonstration, we will use the Iris dataset available through Scikit-learn. It contains measurements of flowers belonging to three species: Setosa, Versicolor, and Virginica.</p><h3>7. Practical Implementation: Building Both Inference Methods</h3><h3>Step 1 — Install the Required Libraries</h3><p>Open the VS Code terminal and execute:</p><pre>py -m pip install pandas scikit-learn fastapi uvicorn joblib</pre><h3>Step 2 — Create the Project Structure</h3><p>Create a folder named ML_Inference_Project.</p><pre>ML_Inference_Project/<br>│<br>├── train_model.py<br>├── app.py<br>├── batch_predict.py<br>└── requirements.txt</pre><h3>Step 3 — Train and Save the Machine Learning Model</h3><p>Create train_model.py.</p><pre>import pandas as pd<br>import joblib</pre><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier</pre><pre># Load dataset<br>iris = load_iris()</pre><pre>X = iris.data<br>y = iris.target</pre><pre># Split dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre># Create model<br>model = RandomForestClassifier(<br>    n_estimators=100,<br>    random_state=42<br>)</pre><pre># Train model<br>model.fit(X_train, y_train)</pre><pre># Save model and class names<br>joblib.dump(<br>    {<br>        &quot;model&quot;: model,<br>        &quot;target_names&quot;: iris.target_names.tolist()<br>    },<br>    &quot;iris_model.pkl&quot;<br>)</pre><pre># Create sample batch input<br>test_data = pd.DataFrame(<br>    X_test[:5],<br>    columns=iris.feature_names<br>)</pre><pre>test_data.to_csv(&quot;batch_input.csv&quot;, index=False)</pre><pre>print(&quot;Model trained and saved successfully!&quot;)<br>print(&quot;Sample batch input created!&quot;)<br>print(&quot;Model accuracy:&quot;, model.score(X_test, y_test))</pre><p>Run:</p><pre>py train_model.py</pre><p>The program trains a Random Forest Classifier, saves the model, and creates a CSV file containing five sample records.</p><h3>Step 4 — Implement Batch Inference</h3><p>Create batch_predict.py.</p><pre>import pandas as pd<br>import joblib</pre><pre># Load model<br>saved_data = joblib.load(&quot;iris_model.pkl&quot;)</pre><pre>model = saved_data[&quot;model&quot;]<br>target_names = saved_data[&quot;target_names&quot;]</pre><pre># Read CSV file<br>data = pd.read_csv(&quot;batch_input.csv&quot;)</pre><pre># Generate predictions<br>predictions = model.predict(data)</pre><pre># Convert numbers into flower names<br>data[&quot;Predicted Species&quot;] = [<br>    target_names[int(p)] for p in predictions<br>]</pre><pre># Save results<br>data.to_csv(&quot;batch_predictions.csv&quot;, index=False)</pre><pre>print(&quot;Batch inference completed!&quot;)<br>print(data)</pre><p>Run:</p><pre>py batch_predict.py</pre><p>The program reads multiple records, generates predictions together, and saves the results in batch_predictions.csv.</p><h3>Step 5 — Implement Real-Time Inference Using FastAPI</h3><p>Create app.py.</p><pre>import joblib</pre><pre>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel</pre><pre>app = FastAPI(title=&quot;Machine Learning Inference API&quot;)</pre><pre># Load trained model<br>saved_data = joblib.load(&quot;iris_model.pkl&quot;)</pre><pre>model = saved_data[&quot;model&quot;]<br>target_names = saved_data[&quot;target_names&quot;]</pre><pre>class FlowerInput(BaseModel):<br>    features: list[float]</pre><pre>@app.post(&quot;/predict&quot;)<br>def predict(data: FlowerInput):</pre><pre>    if len(data.features) != 4:<br>        raise HTTPException(<br>            status_code=400,<br>            detail=&quot;Provide exactly 4 measurements.&quot;<br>        )</pre><pre>    prediction = model.predict([data.features])[0]</pre><pre>    return {<br>        &quot;predicted_species&quot;: target_names[int(prediction)]<br>    }</pre><pre>@app.post(&quot;/predict-batch&quot;)<br>def predict_batch(data: list[FlowerInput]):</pre><pre>    if not data:<br>        raise HTTPException(<br>            status_code=400,<br>            detail=&quot;Provide at least one record.&quot;<br>        )</pre><pre>    if any(len(item.features) != 4 for item in data):<br>        raise HTTPException(<br>            status_code=400,<br>            detail=&quot;Every record needs exactly 4 measurements.&quot;<br>        )</pre><pre>    records = [item.features for item in data]</pre><pre>    predictions = model.predict(records)</pre><pre>    return {<br>        &quot;predictions&quot;: [<br>            target_names[int(p)] for p in predictions<br>        ]<br>    }</pre><p>The API provides two endpoints:</p><ul><li>/predict accepts one flower record.</li><li>/predict-batch accepts multiple flower records.</li></ul><h3>Step 6 — Run the API</h3><p>Open the terminal inside the project folder and execute:</p><pre>py -m uvicorn app:app --reload</pre><p>Open this address in your browser:</p><p><a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a></p><p>FastAPI provides an interactive documentation page where we can test the endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*ZAu0Ffz8rkSyaY-w4b_a9A.png" /></figure><h3>Step 7 — Test Real-Time Inference</h3><p>Open the /predict endpoint and click <strong>Try it out</strong>.</p><p>Enter:</p><pre>{<br>  &quot;features&quot;: [5.1, 3.5, 1.4, 0.2]<br>}</pre><p>Click Execute.</p><p>Example response:</p><pre>{<br>  &quot;predicted_species&quot;: &quot;setosa&quot;<br>}</pre><p>This demonstrates how one incoming request produces a prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*FYC5swR07TMi0wwUeYaKPQ.png" /></figure><h3>Step 8 — Test Batch Inference Through the API</h3><p>Open /predict-batch and enter:</p><pre>[<br>  {<br>    &quot;features&quot;: [5.1, 3.5, 1.4, 0.2]<br>  },<br>  {<br>    &quot;features&quot;: [6.4, 3.2, 4.5, 1.5]<br>  },<br>  {<br>    &quot;features&quot;: [6.7, 3.0, 5.2, 2.3]<br>  }<br>]</pre><p>Click Execute.</p><p>The API returns predictions for all three records in one request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*cyOFhbRjq4eprY5ZZTOj6A.png" /></figure><h3>8. Understanding the Practical Results</h3><p>Our project demonstrates two different ways of using the same trained model.</p><p>In batch processing, the program reads multiple records from a CSV file, generates predictions, and saves them into a new file.</p><p>In real-time processing, the FastAPI application receives an individual request and returns a prediction.</p><p>The API also supports multiple records through its batch endpoint.</p><p>This demonstrates that batch and real-time inference are not necessarily different machine learning algorithms. They are different ways of organizing and delivering model predictions.</p><h3>9. Advantages and Limitations</h3><h3>Batch Inference Advantages</h3><ul><li>Processes multiple records together.</li><li>Suitable for large datasets.</li><li>Supports scheduled execution.</li><li>Useful for reports and forecasting.</li></ul><h3>Real-Time Inference Advantages</h3><ul><li>Generates predictions when requests arrive.</li><li>Supports interactive applications.</li><li>Provides quick responses.</li><li>Can be integrated with websites and mobile applications.</li></ul><h3>Challenges</h3><p>Batch inference may produce delayed results and require significant resources for large datasets.</p><p>Real-time inference requires careful management of response time, server load, availability, and input validation.</p><p>Both approaches also depend on the quality and freshness of the trained model and incoming data.</p><h3>10. How to Choose the Right Inference Method</h3><p>Choose batch inference when:</p><ul><li>Predictions can be generated later.</li><li>Large numbers of records must be processed.</li><li>The application produces scheduled reports.</li><li>Processing efficiency is more important than immediate responses.</li></ul><p>Choose real-time inference when:</p><ul><li>Users need predictions immediately.</li><li>The application requires interactive decisions.</li><li>Each request needs an individual response.</li><li>Low response latency is important.</li></ul><p>Some real-world applications use both approaches. An e-commerce company, for example, can generate recommendations in advance using batch inference and respond to new customer activity using real-time inference.</p><h3>11. Future Scope</h3><p>Machine learning inference systems continue to develop as applications become larger and more complex.</p><p>Important future improvements include:</p><ul><li><strong>Model Optimization:</strong> Quantization and optimized model formats can reduce model size and improve performance.</li><li><strong>GPU-Based Inference:</strong> GPUs can accelerate suitable workloads.</li><li><strong>Distributed Batch Processing:</strong> Large datasets can be processed across multiple machines.</li><li><strong>Model Monitoring:</strong> Developers can monitor response time, failures, and prediction quality.</li><li><strong>Edge Inference:</strong> Models can run directly on mobile phones, cameras, and embedded devices.</li><li><strong>Auto-Scaling:</strong> Cloud infrastructure can adjust resources according to incoming requests.</li></ul><h3>Conclusion: Choosing the Right Way to Make Predictions</h3><p>Machine learning inference is an essential step in turning a trained model into a useful application.</p><p>Batch inference focuses on processing multiple records together when immediate responses are not necessary. Real-time inference focuses on generating predictions when requests arrive.</p><p>In our practical project, we used Python and Scikit-learn to train a classification model, Pandas to process batch records, and FastAPI to expose prediction endpoints.</p><p>The main lesson is that <strong>a good machine learning system is not only about choosing an accurate model. It is also about choosing the right way to deliver its predictions.</strong></p><p>Understanding both approaches helps developers design systems that are efficient, responsive, and suitable for real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b890e6be9456" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>