Python for ML & FastAPI

Okay, let's break down learning Python for Machine Learning (ML) and FastAPI backend development. We'll go step-by-step, keeping things simple with examples.

Think of it like building with LEGOs:

  1. Learn the basic LEGO bricks: Python Fundamentals.

  2. Learn specialized LEGO Technic parts: Libraries for ML & Web Dev.

  3. Learn how to build cool structures: Apply these to ML models and web APIs.


Phase 1: Python Fundamentals (The Basic LEGO Bricks)

These are essential for everything in Python.

  1. What is Python & Setup:

    • Concept: A readable, versatile programming language. Great for beginners and powerful enough for complex tasks.

    • Action: Install Python on your computer (from python.org). Learn how to run a Python file (.py) from your terminal/command prompt.

    • Example:

              # save this as hello.py
        print("Hello, World!")
        # Run in terminal: python hello.py
      
  2. Basic Syntax & Variables:

    • Concept: How to write Python code. Variables are like labeled boxes to store information. Python uses indentation (spaces) to define code blocks, which is important!

    • Example:

              message = "Learning Python" # Storing text (string) in a variable
        count = 10               # Storing a whole number (integer)
        price = 99.95            # Storing a number with decimals (float)
        is_learning = True       # Storing True/False (boolean)
      
        print(message)
        print(count)
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  3. Data Types:

    • Concept: Different kinds of information Python can handle.

      • int: Whole numbers (e.g., 5, -10)

      • float: Decimal numbers (e.g., 3.14, -0.5)

      • str: Text (strings), enclosed in quotes (e.g., "Hello", 'Python')

      • bool: True or False

    • Example:

              age = 30
        temperature = 25.5
        name = "Alice"
        active = False
      
        print(type(age)) # Output: <class 'int'>
        print(type(name)) # Output: <class 'str'>
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  4. Data Structures (Ways to group data):

    • Lists []: Ordered, changeable collections. Like a shopping list.

    • Tuples (): Ordered, unchangeable collections. Like fixed coordinates.

    • Dictionaries {}: Unordered collections of key: value pairs. Like a real dictionary (word: definition).

    • Sets {}: Unordered collections of unique items. Like a group of distinct friends.

    • Example:

              # List
        fruits = ["apple", "banana", "cherry"]
        fruits.append("orange") # Add an item
        print(fruits[0]) # Access first item: "apple"
      
        # Tuple
        coordinates = (10, 20)
        # coordinates[0] = 5 # This would cause an error! Tuples are immutable.
        print(coordinates[1]) # Access second item: 20
      
        # Dictionary
        student = {"name": "Bob", "age": 25, "major": "Physics"}
        print(student["name"]) # Access value by key: "Bob"
        student["age"] = 26 # Change a value
        print(student)
      
        # Set
        unique_numbers = {1, 2, 3, 2, 1}
        print(unique_numbers) # Output: {1, 2, 3} (duplicates removed)
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  5. Operators:

    • Concept: Symbols that perform operations.

      • Arithmetic: +, -, , /, % (modulo/remainder), * (exponent)

      • Comparison: == (equal to), != (not equal), >, <, >=, <=

      • Logical: and, or, not

    • Example:

              x = 10
        y = 3
        print(x + y)   # 13
        print(x / y)   # 3.33...
        print(x % y)   # 1 (remainder)
        print(x > y)   # True
        print(x == 10 and y < 5) # True
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  6. Control Flow (Making Decisions & Repeating):

    • if, elif, else: Run code based on conditions.

    • for loop: Repeat code for each item in a sequence (like a list).

    • while loop: Repeat code as long as a condition is true.

    • Example:

              # if/elif/else
        grade = 75
        if grade >= 90:
            print("A")
        elif grade >= 80:
            print("B")
        elif grade >= 70:
            print("C")
        else:
            print("Fail") # Output: C
      
        # for loop
        colors = ["red", "green", "blue"]
        for color in colors:
            print(f"Color: {color}") # f-string is a handy way to format strings
      
        # while loop
        counter = 0
        while counter < 3:
            print(f"Counter is {counter}")
            counter = counter + 1 # Or counter += 1
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  7. Functions:

    • Concept: Reusable blocks of code that perform a specific task. Makes code organized and avoids repetition.

    • Example:

              # Define a function
        def greet(name):
            print(f"Hello, {name}!")
      
        # Call the function
        greet("Alice") # Output: Hello, Alice!
        greet("Bob")   # Output: Hello, Bob!
      
        # Function that returns a value
        def add_numbers(num1, num2):
            return num1 + num2
      
        sum_result = add_numbers(5, 3)
        print(sum_result) # Output: 8
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  8. Modules & Packages (Using other people's code):

    • Concept: Python comes with built-in modules (like math, random). You can also install external packages (libraries) using pip (Python's package installer).

    • Example:

              import math # Import the built-in math module
        print(math.sqrt(16)) # Use a function from the module: 4.0
      
        import random
        print(random.randint(1, 6)) # Print a random number between 1 and 6
      
        # In your terminal (NOT in the Python script):
        # pip install requests  (Installs an external package for making web requests)
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  9. File Handling:

    • Concept: Reading from and writing to files.

    • Example:

              # Write to a file
        # 'w' mode overwrites the file if it exists
        with open("my_file.txt", "w") as f:
            f.write("This is the first line.\n")
            f.write("This is the second line.\n")
      
        # Read from a file
        # 'r' mode reads the file
        with open("my_file.txt", "r") as f:
            content = f.read()
            print(content)
      
        # 'a' mode appends to the end of the file
        with open("my_file.txt", "a") as f:
            f.write("This is appended.\n")
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

      (with open(...) is good because it automatically closes the file for you)

  10. Error Handling (try/except):

    • Concept: Handling potential errors gracefully without crashing the program.

    • Example:

              try:
            result = 10 / 0 # This will cause a ZeroDivisionError
            print(result)
        except ZeroDivisionError:
            print("Oops! You can't divide by zero.")
        except Exception as e: # Catch any other type of error
            print(f"An unexpected error occurred: {e}")
      
        print("Program continues after handling the error.")
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END


Phase 2: Intermediate Python (Useful for structured code)

  1. Object-Oriented Programming (OOP):

    • Concept: Organizing code using "objects" which have data (attributes) and behaviors (methods). Think of a Car object having attributes like color, model and methods like start_engine(), drive(). Uses class keyword. Important for understanding many libraries.

    • Example:

              class Dog:
            # Constructor (runs when you create a Dog object)
            def __init__(self, name, breed):
                self.name = name # Attribute
                self.breed = breed # Attribute
      
            # Method
            def bark(self):
                print(f"{self.name} says Woof!")
      
        my_dog = Dog("Buddy", "Golden Retriever") # Create an object (instance)
        print(my_dog.name) # Access attribute: Buddy
        my_dog.bark()     # Call method: Buddy says Woof!
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  2. List Comprehensions:

    • Concept: A concise way to create lists.

    • Example:

              # Traditional way
        squares = []
        for i in range(5): # range(5) gives numbers 0, 1, 2, 3, 4
            squares.append(i * i)
        print(squares) # Output: [0, 1, 4, 9, 16]
      
        # List comprehension way
        squares_comp = [i * i for i in range(5)]
        print(squares_comp) # Output: [0, 1, 4, 9, 16]
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  3. Virtual Environments:

    • Concept: Isolated Python environments for each project. Prevents package version conflicts between projects. Highly recommended!

    • Action (in terminal):

              # Create a virtual environment named 'venv' (common name)
        python -m venv venv
      
        # Activate it (syntax varies by OS)
        # Windows (cmd/powershell):
        # venv\Scripts\activate
        # MacOS/Linux (bash/zsh):
        # source venv/bin/activate
      
        # Your terminal prompt will usually change to show (venv)
      
        # Install packages within the active environment
        pip install numpy pandas
      
        # Deactivate when done
        # deactivate
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Bash

      IGNORE_WHEN_COPYING_END


Phase 3: Python for Machine Learning (Specialized LEGO Technic parts for ML)

Activate your virtual environment before installing these! pip install numpy pandas matplotlib scikit-learn

  1. NumPy (Numerical Python):

    • Concept: The fundamental package for numerical operations. Provides efficient array objects (like lists, but faster for math) and mathematical functions.

    • Example:

              import numpy as np # Standard way to import numpy
      
        # Create a NumPy array
        a = np.array([1, 2, 3, 4, 5])
        b = np.array([[1, 2], [3, 4]]) # 2D array (matrix)
      
        print(a)
        print(b.shape) # Shape of the array (rows, columns): (2, 2)
      
        # Element-wise operations (much faster than Python lists)
        print(a * 2) # Output: [ 2  4  6  8 10]
        print(np.sqrt(a))
      
        # Basic stats
        print(np.mean(a)) # Average: 3.0
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  2. Pandas (Data Analysis Library):

    • Concept: Built on NumPy, Pandas provides high-performance, easy-to-use data structures (like DataFrame - think Excel spreadsheet) and data analysis tools. Essential for cleaning, transforming, and analyzing data.

    • Example:

              import pandas as pd # Standard way to import pandas
      
        # Create a DataFrame (like a table)
        data = {'Name': ['Alice', 'Bob', 'Charlie'],
                'Age': [25, 30, 22],
                'City': ['New York', 'Paris', 'London']}
        df = pd.DataFrame(data)
        print(df)
      
        # Select a column (Series)
        print(df['Age'])
      
        # Basic info and stats
        print(df.info())
        print(df.describe())
      
        # Load data from a CSV file (very common)
        # Assuming you have a file 'data.csv'
        # df_from_csv = pd.read_csv('data.csv')
        # print(df_from_csv.head()) # Show first 5 rows
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  3. Matplotlib & Seaborn (Data Visualization):

    • Concept: Libraries for creating static, animated, and interactive visualizations (plots and graphs). Matplotlib is the foundation, Seaborn builds on it for more attractive statistical plots.

    • Example (using Matplotlib):

              import matplotlib.pyplot as plt
        import numpy as np
      
        x = np.linspace(0, 10, 100) # 100 numbers from 0 to 10
        y = np.sin(x)
      
        plt.plot(x, y) # Create a line plot
        plt.title("Sine Wave")
        plt.xlabel("X-axis")
        plt.ylabel("Y-axis")
        plt.grid(True)
        plt.show() # Display the plot
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

    • Example (using Pandas built-in plotting & Matplotlib):

              import pandas as pd
        import matplotlib.pyplot as plt
      
        data = {'Category': ['A', 'B', 'C', 'D'], 'Values': [10, 25, 15, 30]}
        df = pd.DataFrame(data)
      
        df.plot(kind='bar', x='Category', y='Values', legend=False)
        plt.title("Bar Chart Example")
        plt.ylabel("Value Count")
        plt.xticks(rotation=0) # Keep category names horizontal
        plt.tight_layout() # Adjust plot to prevent labels overlapping
        plt.show()
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

  4. Scikit-learn (Machine Learning Library):

    • Concept: The go-to library for traditional ML algorithms. Provides tools for:

      • Data Preprocessing: Scaling features, encoding categorical variables.

      • Model Selection: Choosing the right algorithm.

      • Training: Fitting models to data (.fit()).

      • Evaluation: Checking model performance (accuracy, etc.).

      • Common Algorithms: Linear Regression, Logistic Regression, K-Nearest Neighbors, Support Vector Machines (SVM), Decision Trees, Random Forests, K-Means Clustering, etc.

    • Example (Simple Linear Regression):

              import numpy as np
        from sklearn.model_selection import train_test_split
        from sklearn.linear_model import LinearRegression
        from sklearn.metrics import mean_squared_error
      
        # 1. Sample Data (Feature: Study Hours, Target: Exam Score)
        # Usually loaded from Pandas DataFrame
        X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) # Feature(s) must be 2D
        y = np.array([50, 55, 65, 68, 75, 78, 85, 88, 92, 96]) # Target
      
        # 2. Split data into Training and Testing sets
        # Test set is used to evaluate the trained model on unseen data
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
        # test_size=0.2 means 20% for testing, 80% for training
        # random_state ensures the split is the same every time (for reproducibility)
      
        # 3. Choose and Create a Model
        model = LinearRegression()
      
        # 4. Train the Model (Fit the model to the training data)
        model.fit(X_train, y_train)
      
        # 5. Make Predictions on the Test Set
        y_pred = model.predict(X_test)
      
        # 6. Evaluate the Model
        mse = mean_squared_error(y_test, y_pred)
        print(f"Mean Squared Error: {mse}")
        print(f"Model Coefficient (slope): {model.coef_}")
        print(f"Model Intercept: {model.intercept_}")
      
        # 7. Predict on new data
        new_hours = np.array([[6.5]]) # Needs to be 2D
        predicted_score = model.predict(new_hours)
        print(f"Predicted score for {new_hours[0][0]} hours: {predicted_score[0]}")
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

Key ML Concepts to Understand with Scikit-learn:

  • Features vs. Target: Features (X) are the input variables used to predict the Target (y).

  • Supervised Learning: Learning from labeled data (you have both X and y). Examples: Regression (predicting a number), Classification (predicting a category).

  • Unsupervised Learning: Learning from unlabeled data (you only have X). Examples: Clustering (grouping similar data points).

  • Training Set vs. Test Set: Train the model on one part of the data, test its performance on a separate, unseen part.

  • Model Evaluation Metrics: How good is the model? (Accuracy, Precision, Recall, F1-score for classification; MSE, R-squared for regression).


Phase 4: Python for FastAPI Backend Development (Specialized LEGO Technic parts for Web APIs)

Activate your virtual environment! pip install fastapi uvicorn[standard] pydantic

  1. Basic Web Concepts (Briefly):

    • HTTP: The protocol browsers and servers use to communicate (Requests/Responses).

    • API (Application Programming Interface): A way for different software components to talk to each other. Web APIs allow communication over the internet.

    • REST API: A common style for designing web APIs using standard HTTP methods (GET, POST, PUT, DELETE) for resources (e.g., /users, /items).

    • JSON (JavaScript Object Notation): A standard text format for sending data over the web. Looks very similar to Python dictionaries.

  2. FastAPI Introduction:

    • Concept: A modern, fast (high-performance) web framework for building APIs with Python. Known for its speed, ease of use, automatic documentation, and data validation using type hints.

    • Key Feature: Uses Python type hints (str, int, etc.) for automatic data validation and API documentation.

  3. Creating a Basic FastAPI App:

    • Concept: Define API endpoints (URLs) and the functions that handle requests to those endpoints.

    • Example (main.py):

              from fastapi import FastAPI
      
        # Create a FastAPI instance
        app = FastAPI()
      
        # Define a "path operation decorator" for the root URL ("/")
        # GET is the HTTP method
        @app.get("/")
        def read_root():
            # Return a dictionary, FastAPI automatically converts it to JSON
            return {"message": "Hello World"}
      
        # Another endpoint
        @app.get("/items/{item_id}") # Path parameter {item_id}
        def read_item(item_id: int, q: str | None = None): # Type hints! item_id MUST be int. q is optional string.
            # item_id comes from the path
            # q is an optional query parameter (e.g., /items/5?q=somequery)
            response = {"item_id": item_id}
            if q:
                response.update({"q": q})
            return response
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

    • Running the App (in terminal, in the same directory as main.py):

              uvicorn main:app --reload
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Bash

      IGNORE_WHEN_COPYING_END

      • main: the file main.py.

      • app: the object app = FastAPI() inside main.py.

      • --reload: Makes the server restart automatically when you save code changes.

    • Accessing: Open your browser to http://127.0.0.1:8000. You'll see {"message": "Hello World"}.

    • Interactive Docs: Go to http://127.0.0.1:8000/docs. FastAPI automatically generated interactive API documentation! Try out the /items/{item_id} endpoint there.

  4. Pydantic (Data Validation):

    • Concept: FastAPI uses Pydantic heavily for defining data shapes and validation. You define data models using Python classes with type hints.

    • Example (Adding a POST request with a request body):

              from fastapi import FastAPI
        from pydantic import BaseModel # Import BaseModel
      
        # Define a data model using Pydantic
        class Item(BaseModel):
            name: str
            description: str | None = None # Optional field
            price: float
            tax: float | None = None
      
        app = FastAPI()
      
        @app.get("/")
        def read_root():
            return {"message": "Hello World"}
      
        @app.get("/items/{item_id}")
        def read_item(item_id: int, q: str | None = None):
            response = {"item_id": item_id}
            if q:
                response.update({"q": q})
            return response
      
        # Endpoint to create an item (using POST method)
        @app.post("/items/")
        def create_item(item: Item): # Request body will be validated against the Item model
            print(f"Received item: {item.name}, Price: {item.price}")
            item_dict = item.dict() # Convert Pydantic model to dictionary
            if item.tax:
                price_with_tax = item.price + item.tax
                item_dict.update({"price_with_tax": price_with_tax})
            return item_dict
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

    • Testing: Use the /docs page to send a POST request to /items/. FastAPI will automatically show you the expected JSON format and validate your input. If you send bad data (e.g., price as a string), you'll get an automatic error response.

  5. Async (async/await):

    • Concept: FastAPI supports asynchronous code, which allows your server to handle many requests concurrently without waiting for slow operations (like network calls or database queries) to finish. This is key to its performance.

    • Example (Simple async endpoint):

              import asyncio
        from fastapi import FastAPI
      
        app = FastAPI()
      
        # Define an async function using 'async def'
        @app.get("/slow-task")
        async def run_slow_task():
            print("Task started...")
            # Simulate a slow I/O operation (like waiting for a database)
            await asyncio.sleep(3) # Pauses this function, lets server handle others
            print("Task finished!")
            return {"status": "Task completed after 3 seconds"}
      

      IGNORE_WHEN_COPYING_START

      content_copy download

      Use code with caution.Python

      IGNORE_WHEN_COPYING_END

    • Note: You don't have to use async def everywhere, but it's essential for I/O-bound tasks to keep your server responsive.


Phase 5: Putting It Together & Next Steps

  • Connecting ML & FastAPI: You can load a trained Scikit-learn model (e.g., save it with joblib or pickle) inside your FastAPI app. Create an endpoint that accepts input data (validated with Pydantic), uses the loaded model to make a prediction, and returns the prediction as a JSON response.

  • Databases: Learn how to connect FastAPI to databases (like PostgreSQL or MySQL) using libraries like SQLAlchemy (ORM - Object Relational Mapper) or simpler database drivers.

  • Authentication & Authorization: Secure your API endpoints.

  • Testing: Write tests for your FastAPI application (FastAPI makes this easy).

  • Deployment: Learn how to deploy your FastAPI app to a server (e.g., using Docker, cloud platforms like AWS, Google Cloud, Heroku).

  • Deep Learning (Advanced ML): Explore libraries like TensorFlow/Keras or PyTorch for complex models (neural networks).

How to Learn Effectively:

  1. Code Along: Don't just read. Type out the examples, run them, modify them, break them, fix them.

  2. Practice: Find small coding exercises (e.g., on sites like LeetCode, HackerRank, Codewars - focus on fundamentals first).

  3. Build Small Projects:

    • Fundamentals: A simple calculator, a text-based game.

    • ML: Analyze a simple dataset (like the Iris dataset or Titanic dataset from Kaggle), build a basic prediction model.

    • FastAPI: Create a simple To-Do list API, a basic blog API.

    • Combined: An API that takes some user input and returns a prediction from a simple ML model.

  4. Read Documentation: Get comfortable looking up things in the official Python, NumPy, Pandas, Scikit-learn, and FastAPI documentation.

  5. Ask Questions: Use forums like Stack Overflow (search first!) or communities.

  6. Be Patient: Learning takes time and consistent effort. Don't get discouraged!

This roadmap covers the core areas. Start with Phase 1 and build a solid foundation before moving on. Good luck!

0
Subscribe to my newsletter

Read articles from Singaraju Saiteja directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Singaraju Saiteja
Singaraju Saiteja

I am an aspiring mobile developer, with current skill being in flutter.