← Back to Main Page

Module 4: Build Sprint 3

Understanding Your Third Ticket

Learn how to approach your third ticket in the Labs project and understand the development workflow.

Third Ticket Details

View your third ticket details and requirements on GitHub:

Third Ticket Documentation

Approaching Your Third Feature

Learn how to implement a machine learning model interface, train and tune models, and integrate them with your API.

Implementation Checklist

  • Create a Jupyter notebook for model testing and tuning
  • Train and tune at least 3 different models
  • Implement the Machine Learning interface class
  • Add model serialization functionality
  • Integrate the model with the API
  • Test model predictions and probabilities
  • Ensure proper model saving and loading
  • Add model information endpoint
# Example Machine Learning Implementation

from pandas import DataFrame
from sklearn.ensemble import RandomForestClassifier
from joblib import dump, load
from datetime import datetime


class Machine:
    """Machine Learning interface for monster predictions."""
    
    def __init__(self, df: DataFrame):
        """Initialize the machine learning model.
        
        Args:
            df: DataFrame containing training data
        """
        self.name = "Random Forest Classifier"
        self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        target = df["Rarity"]
        features = df.drop(columns=["Rarity"])
        self.model = RandomForestClassifier()
        self.model.fit(features, target)

    def __call__(self, pred_basis: DataFrame):
        """Make predictions using the trained model.
        
        Args:
            pred_basis: DataFrame of features for prediction
            
        Returns:
            Tuple of (prediction, probability)
        """
        prediction = self.model.predict(pred_basis)[0]
        probability = self.model.predict_proba(pred_basis)[0]
        return prediction, probability

    def save(self, filepath: str):
        """Save the trained model to disk.
        
        Args:
            filepath: Path to save the model
        """
        dump(self.model, filepath)

    @classmethod
    def open(cls, filepath: str):
        """Load a saved model from disk.
        
        Args:
            filepath: Path to the saved model
            
        Returns:
            Loaded Machine instance
        """
        model = load(filepath)
        instance = cls.__new__(cls)
        instance.model = model
        return instance

    def info(self) -> str:
        """Get information about the model.
        
        Returns:
            String containing model name and timestamp
        """
        return f"Model: {self.name}, Initialized: {self.timestamp}"


# Example usage in FastAPI endpoint
@app.get("/model")
async def get_model_info():
    machine = Machine(monster_db.dataframe())
    return {"info": machine.info()}