Configure an ML Model as a Perceptor

In this tutorial, we will walk through how to integrate a trained machine learning (ML) model into your Composabl agent as a Perceptor. A perceptor allows your agent to interpret data from sensors, process it using a machine learning model, and output new variables that will help the agent make better decisions.

The goal is to publish a pre-trained ML model as a perceptor that adds a new layer of perception to your agent, enabling it to process sensor data in a more advanced way. This could be useful in a variety of scenarios, such as predictive maintenance, anomaly detection, or autonomous decision-making.


Step 1: Understanding the Perceptor

A Perceptor in Composabl is a module in the perception layer that inputs sensor data, processes it (potentially using an ML model), and outputs new variables that are automatically added to the list of available sensors.

For this example, let’s assume we are building a perceptor that uses a trained machine learning model to predict thermal runaway in a system.


Step 2: Setting Up the Trained Model

We will use a pre-trained ML model stored as a pickle file to predict thermal runaway based on certain temperature and chemical sensor readings. Here’s how to set up the trained ML model for use as a perceptor.

  1. Store the ML Model: Assume the ML model has been trained and saved as a .pkl file. For this example, the model is stored in the path: ml_models/ml_predict_temperature.pkl.

  2. Load the ML Model in the Perceptor: In the perceptor class, we will load the model and define how it processes the sensor data.


Step 3: Creating the Perceptor

Now, we’ll create the perceptor using the trained ML model to process the sensor data and predict thermal runaway events. The perceptor will be responsible for calling the model and returning the prediction as a new sensor variable.

We can start by creating the preceptor by using the Composable CLI with the following command:

composable preceptor new

The new preceptor will have the following file structure:

.└── perceptor_name/    
    ├── perceptor_name/    
        │   ├── __init__.py    
        │   └── perceptor.py    
    ├── pyproject.toml    
    └── README.md

3.1. Configuring your pyproject.toml file

[project]

name = "perc" # Keep this as the same name as the directory
version = "0.1.0"
description = "perc" # You can change this to a description of your project
authors = [    
    { name = "John Doe", email = "john.doe@composabl.com" },
] # Change this to your name and email
dependencies = [    
    "composabl-core",    
    "<third-party-lib>", # Add any third-party dependencies here
]

[composabl]# This metadata should not be changed with exption of the entrypoint
# after the : marker if you change the name of the class. Those names
# should match.
type = "perceptor"entrypoint = "perc.perceptor:DemoPerceptor"

3.2. Implementing the Perceptor in the perceptor.py file

Here’s the Python code to create the perceptor:

import pickle
from composabl import Perceptor, PerceptorImpl
from sensors import sensors  # Assuming sensors are already defined

class ThermalRunawayPredict(PerceptorImpl):
    def __init__(self, *args, **kwargs):
        self.last_Tc = 0  # Store the last observed temperature
        self.ml_model = pickle.load(open("ml_models/ml_predict_temperature.pkl", 'rb'))  # Load the trained ML model

    async def compute(self, obs_spec, obs):
        # Convert the observation to a dictionary using sensor names
        if type(obs) != dict:
            obs_keys = [s.name for s in sensors]
            obs = dict(zip(obs_keys, obs))

        # Calculate delta temperature (change in Tc)
        if self.last_Tc == 0:
            delta_Tc = 5  # Initial change
        else:
            delta_Tc = float(obs['Tc']) - self.last_Tc

        # Prepare the input for the ML model
        X = [[float(obs['Ca']), float(obs['T']), float(obs['Tc']), delta_Tc]]
        
        # Get the prediction from the ML model
        prediction = self.ml_model.predict(X)[0]

        # Update last_Tc for the next iteration
        self.last_Tc = float(obs['Tc'])

        # Return the prediction as a new sensor variable
        return {"thermal_runaway_predict": prediction}

    def filtered_sensor_space(self, obs):
        # Define which sensor values the ML model needs
        return ['T', 'Tc', 'Ca']

In this perceptor:

  • We load the trained machine learning model from a pickle file.

  • The compute() method takes in sensor data (e.g., temperature, chemical concentrations), processes it, and uses the ML model to predict whether a thermal runaway event will occur.

  • The perceptor outputs the prediction as a new sensor variable, thermal_runaway_predict.

3.2. Adding the Perceptor to Your Agent

Once the perceptor is defined, you can login to the Composabl editor and add it to your agent.


Conclusion

In this tutorial, we covered how to publish a trained ML model as a perceptor in Composabl. This allows the agent to integrate more advanced decision-making by processing raw sensor data through a machine learning model and outputting predictions as new sensor variables. This method can be applied in various domains, such as predictive maintenance, anomaly detection, and control systems.

Last updated