<?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 Abdulwajeed Ganiyu on Medium]]></title>
        <description><![CDATA[Stories by Abdulwajeed Ganiyu on Medium]]></description>
        <link>https://medium.com/@ganiyuabdulwajeed2002?source=rss-a8c0c9a65f6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AIG6wRJgc0_6ge_dti-Bxg.jpeg</url>
            <title>Stories by Abdulwajeed Ganiyu on Medium</title>
            <link>https://medium.com/@ganiyuabdulwajeed2002?source=rss-a8c0c9a65f6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:01:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ganiyuabdulwajeed2002/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[A step-by-step approach to building a fast API for deep learning classification projects]]></title>
            <link>https://medium.com/@ganiyuabdulwajeed2002/a-step-by-step-approach-to-building-a-fast-api-for-deep-learning-classification-projects-cbd2ea6bc2f2?source=rss-a8c0c9a65f6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd2ea6bc2f2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Abdulwajeed Ganiyu]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 09:57:10 GMT</pubDate>
            <atom:updated>2023-07-04T09:57:10.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rXPJzwDEPu0kYobK" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Once upon a time machine learning projects often stayed trapped in Jupyter Notebooks never getting a chance to shine in the real world. But then something unique happened — APIs came to the rescue!</p><p>As a machine learning engineer, I felt excited by this new opportunity. APIs were like doors to the internet connecting our models with users, clients, businesses and industries worldwide. So I decided to give it a try and break free from the notebook boundaries.</p><p>The Fast API in particular caught my attention with its promises of speed, simplicity and scalability. It beckoned me to explore the possibilities of liberating my machine-learning models and bringing them to life in the real world. The most exciting aspect of the Fast API was its ability to provide real-time feedback and built-in documentation for my model and API endpoint’s performance all without needing any external testers like Postman.</p><h3>Fast API</h3><p>FastAPI is like a super-speedy and user-friendly tool for developers to create web applications easily. It helps them build APIs (Application Programming Interfaces) — which are like bridges that allow different software programs to talk to each other.</p><p>One of the key advantages of FastAPI is its impressive performance. It leverages the power of asynchronous programming and type annotations to achieve incredible speed making it one of the fastest web frameworks available. This makes it an ideal choice for building APIs that require real-time responses or handle a large number of concurrent requests.</p><h3>Getting the Dataset</h3><p>The dataset used in this article is a collection of dermoscopic images of skin lesions which have been labelled as one of the three types of skin cancer. The dataset was preprocessed and split into training, validation, and test sets. The images were resized and normalized to improve the performance of the model.</p><p>The dataset can be downloaded from <a href="https://www.kaggle.com/datasets/nodoubttome/skin-cancer9-classesisic">here</a>.</p><h3>Setting Up the Environment</h3><p>Setting up an environment for a FastAPI-based deep learning project is the first step towards building an awesome API. Here’s a step-by-step guide to get started:</p><h4>Install Python</h4><p>The latest version of Python can be downloaded from the official Python website (<a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>).</p><h4>Create a Virtual Environment</h4><p>It’s a good practice to work within a virtual environment to avoid conflicts with other Python projects. Open your terminal or command prompt and navigate to your project directory. Then create a virtual environment by running the following command.</p><pre>conda create -n my_env python=3.11.0 </pre><pre>python -m venv my_env</pre><h4>Activate the Virtual Environment</h4><p>Once the virtual environment is created you can activate it with the appropriate command depending on your operating system.</p><pre>conda activate venv</pre><pre>myenv\Scripts\activate</pre><h4>Install Dependencies</h4><p>All the dependencies can be downloaded by creating a file named requirements.txt in the codebase by executing the command below</p><pre>tensorflow<br>fastapi<br>uvicorn<br>python-multipart<br>pillow<br>matplotlib<br>numpy</pre><pre>pip install -r requirements.txt</pre><h3>Implementation</h3><p>With all the necessary dependencies successfully installed, it’s time to dive into the implementation phase. Let’s cover the key processes step by step:</p><ol><li>Import the necessary libraries</li><li>Initialize FastAPI</li><li>Load the deep learning model</li><li>Build functions to preprocess and to predict the image</li><li>Initialize the FastAPI object</li><li>Run and test the FastAPI Application</li></ol><h4>Import the necessary libraries</h4><p>Let’s Begin by importing the required libraries for the project which include FastAPI, TensorFlow, Numpy or any other libraries specific to the deep learning classification task.</p><pre>import numpy as np #  A library for numerical computing in Python.<br>from fastapi import FastAPI, File, UploadFile, HTTPException<br>from fastapi.middleware.cors import CORSMiddleware<br>import uvicorn # ASGI server to run the FastAPI application.<br>import uvicorn<br>from io import BytesIO # A class for working with binary data in memory.<br>from PIL import Image # A library for image processing.<br>from typing import Tuple # A library for type hints.<br>import tensorflow as tf # A library for machine learning.<br>from fastapi.responses import HTMLResponse</pre><h4>Initialize FastAPI</h4><p>You have to create an instance of the FastAPI class. This will serve as the foundation for building the API.</p><pre>app = FastAPI() # Create the FastAPI app</pre><h4>Load the deep learning model</h4><p>Next on our journey is loading the pre-trained deep learning model, which will be the heart and soul of our classification task.</p><p>I will utilize my pre-trained image classifier model, carefully crafted using TensorFlow. The model is proficient in predicting three distinct classes of skin cancer, namely Melanoma, Squamous Cell Carcinoma, and Basal Cell Carcinoma.</p><pre># Load the model<br>MODEL = tf.keras.models.load_model(&#39;&lt;INSERT YOUR SAVEDMODEL FILE PATH HERE&gt;&#39;) <br># The class names of the model<br>CLASS_NAMES = [&#39;basal cell carcinoma&#39;, &#39;melanoma&#39;, &#39;squamous cell carcinoma&#39;] </pre><h4>Build functions to preprocess and predict the image</h4><p>Now comes the exciting part of our project — implementing functions that take care of data preprocessing and model prediction. These functions play a crucial role in our system as they handle the preparation of input data and utilize the model to make accurate predictions based on that data.</p><pre>def read_file_as_image(data) -&gt; Tuple[np.ndarray, Tuple[int, int]]: # A function to read the image file as a numpy array<br>    img = Image.open(BytesIO(data)).convert(&#39;RGB&#39;) # Open the image and convert it to RGB color space<br>    img_resized = img.resize((180, 180), resample=Image.BICUBIC) # Resize the image to 180 x 180<br>    image = np.array(img_resized) # Convert the image to a numpy array<br>    return image, img_resized.size # Return the image and its size</pre><h4>Initialize the FastAPI object</h4><p>Let’s move on to a crucial step — initializing the FastAPI object. Here, we’ll set up our FastAPI application by defining the API endpoints. To achieve this, we’ll make use of FastAPI’s decorators like @app.get or @app.post. These decorators allow us to specify the URL paths and HTTP methods associated with each endpoint, creating a well-structured API.</p><pre>@app.post(&quot;/predict&quot;) # A decorator to create a route for the predict endpoint<br>async def predict(file: UploadFile = File(...)): # The function that will be executed when the endpoint is called<br>    try: # A try block to handle any errors that may occur<br>        image, img_size = read_file_as_image(await file.read()) # Read the image file<br>        img_batch = np.expand_dims(image, 0) # Add an extra dimension to the image so that it matches the input shape of the model<br><br>        predictions = MODEL.predict(img_batch) # Make a prediction<br>        predicted_class = CLASS_NAMES[np.argmax(predictions[0])] # Get the predicted class<br>        confidence = np.max(predictions[0]) # Get the confidence of the prediction<br> <br>        return { # Return the prediction<br>            &#39;class&#39;: predicted_class,   <br>            &#39;confidence&#39;: float(confidence) <br>        }<br>    except Exception as e: # If an error occurs<br>        raise HTTPException(status_code=400, detail=str(e)) # Raise an HTTPException with the error message</pre><h4>Run and test the FastAPI Application</h4><p>It’s time to put our FastAPI application to the test! We’ll run the application and carefully examine its performance to ensure everything works seamlessly as intended. To validate its functionality, we can utilize helpful tools like Swagger UI or Postman. By sending sample requests to our API and analyzing the responses, we can be confident that our application adeptly handles requests and delivers precise predictions.</p><pre>if __name__ == &quot;__main__&quot;: # If the script is run directly<br>    uvicorn.run(app, host=&quot;localhost&quot;, port=8002) # Run the FastAPI app using uvicorn</pre><p>Now, head over to your terminal and run one of the following commands (make sure you are on the same path as the API file):</p><pre>python app.py </pre><p>Upon executing the command, you can expect a result that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*xKjMvsEkaDvNrWc_KQOpAA.png" /></figure><p>Now, it’s time to access the API using the address <a href="http://localhost:8002/">http://localhost:8002</a> Here, 8002 is the designated port number for accessing the API.</p><p>Now, it’s time to put the API to the test and see how accurately it can predict and classify an image of skin cancer into one of the three classes. For this purpose, we can leverage FastAPI’s built-in functionality for testing APIs, as outlined in the official documentation. By following the guidelines provided by FastAPI, we can ensure a comprehensive and thorough evaluation of our API’s performance and classification capabilities. This allows us to gain confidence in our system’s ability to handle real-world scenarios and deliver precise predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOdCilEztIKAKLsA2SyUSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMLwvaoKNWBchar2HKgBAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Icrda80Pocn_ZcMnumwfQ.png" /></figure><p>Once the execution is complete, you’ll receive an HTTP Protocol message in the terminal, indicating whether the API worked successfully or encountered any issues. This message acts as a status report, allowing you to verify the API’s functionality and ensure it is operating as intended. By closely monitoring this message, you can quickly identify any potential problems and take necessary actions to optimize and fine-tune your API for better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*rJeVxUBVH0ZOB0NzZ_eiaQ.png" /></figure><p>we can also take our project to the next level by building a beautiful and user-friendly webpage. This webpage will serve as the interface through which end-users can easily interact with the API. With an intuitive and visually appealing design, users can effortlessly submit their images for skin cancer classification and receive instant predictions. This not only enhances the user experience but also adds a touch of professionalism to our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNkdqNmrX67ggzzHsADp2g.png" /></figure><p>You can get the full code <a href="https://github.com/olanix2002/A-Deep-Learning-Approach-to-Skin-Cancer-Diagnosis">here</a></p><h3>Final Remark</h3><p>As observed in the demonstration above, the API has successfully processed the image and provided accurate predictions. Congratulations on successfully building the Deep Learning API using FastAPI!</p><p>This article aimed to provide you with a clear understanding of the FastAPI concept and guide you in developing your own API for your projects.</p><p>If you found this article helpful and insightful, consider following my Medium profile for more articles on similar topics. Additionally, if you have any questions or would like to connect with me, feel free to reach out to me on <a href="https://www.linkedin.com/in/abdulwajeed-ganiyu/">LinkedIn</a>.</p><p>Thank you for taking the time to read this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd2ea6bc2f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>