# Integrating Machine Learning Models with Fetch.ai Agents for Smarter Decisions

- Anno: 2024
- Tipo: analisi
- Lingua: en
- Pagine: 10
- PDF: https://www.cryptohelvetia.com/api/pdf/integrating-machine-learning-models-with-fetch-ai-agents-for-smarter-decisions
- Pagina: https://www.cryptohelvetia.com/ch-intelligence/pdf/2024/integrating-machine-learning-models-with-fetch-ai-agents-for-smarter-decisions
- Fonte: CH Intelligence, archivio PDF di CryptoHelvetia

> This article explains how to integrate machine learning models with Fetch.ai autonomous agents. It focuses on enabling smarter, customer-centric decisions, using a bank customer churn prediction model as a primary example. The document details the process from data preprocessing and model training to the integration of ML models with Fetch.

medium.com /fetch-ai/integrating-machine-learning-models-with-fetch-ai-agents-for-smarter-decisions-1b…

Kshipra Dhame ⋮ 20-26 minutes ⋮ 08/11/2024

Page 1

Published in

11 min read

Nov 8, 2024

Fetch.ai Agents are autonomous, decentralized agents capable of achieving a particular task while communicating and collaborating with other agents. By embedding machine learning, autonomous agents gain the ability to think and make informed decisions that reflect user goals and drive actions based on real-time data and insights. This article focuses on integrating a machine learning (ML) model into Fetch.ai agents, allowing these agents to make customer-centric decisions. We’ll explore this integration through a bank customer churn prediction model, where AI agents not only predict potential churners but also take proactive steps to retain them.

Why Combine ML Models with Autonomous Agents?

Autonomous agents equipped with ML models gain the ability to independently analyze data, forecast outcomes, and make immediate, context-aware decisions. This integration offers two key advantages:

Automated Decision-Making: Agents can execute follow-up actions autonomously based on predictions, ensuring consistent, timely responses.

Real-Time Responsiveness: By acting immediately on live data, agents provide dynamic feedback and targeted actions, enhancing the customer experience and retention efforts.

## Use Case: Predicting and Preventing Customer Churn in Banking

Customer churn, also known as customer attrition, occurs when a customer stops using a company’s products or services. Churn is a critical metric for companies, especially in subscription-based industries like banking, telecommunications, and insurance, where a consistent revenue stream relies on maintaining a loyal customer base. High churn rates can significantly impact profitability.

Understanding and predicting churn is essential to mitigate its impact. By proactively identifying customers at risk of leaving, companies can intervene with targeted offers, tailored incentives, or enhanced service touchpoints to address customer needs. This approach not only helps in retaining valuable customers but also strengthens overall customer satisfaction.

In this scenario, a machine learning model integrated into a Fetch.ai agent identifies customers who may churn based on various indicators, such as transaction activity, satisfaction scores, and service usage. When a potential churn is detected, the agent can take immediate, automated actions to retain the customer, such as generating a loyalty offer or notifying the customer support team for follow-up. This dynamic, data-driven strategy enables real-time responses that improve retention rates and contribute to a better customer experience.

## Prerequisites

To get the most out of this article, it’s helpful to have:

A Basic Understanding of Machine Learning: Familiarity with core ML concepts like data preprocessing, model training, and evaluation will clarify the model integration steps.

Experience with Python Programming: Since Fetch.ai agents and machine learning models are built and executed in Python, basic knowledge of Python is essential.

Awareness of Fetch.ai AI Agents: While the essentials will be covered, having a general idea of Fetch.ai’s framework and how autonomous agents function will be beneficial.

With these foundations in place, we’re ready to dive into how Machine Learning models can be integrated with Fetch.ai’s autonomous agents

## Step 1: Training a Machine Learning Model to achieve a specific task

This step involves training a machine learning model to predict customer churn based on a structured dataset of customer records. The dataset includes features such as customer demographics, account balance, and product usage patterns, which can help in identifying churn patterns. You can access the dataset here.

Refer to the Google Colab Notebook understand the complete workflow, from data preparation to model training and saving.

## Data Preprocessing

The dataset requires several preprocessing steps to ensure optimal model performance. These steps may include:

Encoding Categorical Variables: Converting categorical fields, such as customer geography and gender, into a format that can be used by the model. One-hot encoding is used to create binary columns for each category.

Scaling Numerical Features: Applying MinMax scaling to numerical features to standardize their range, improving the model’s ability to learn from the data. Handling Class Imbalance: As churn events may be relatively rare, oversampling techniques like SMOTE (Synthetic Minority Oversampling Technique) are applied to balance the dataset.

## Model Selection and Training

The notebook uses a neural network model, built and trained with TensorFlow and Keras, to predict customer churn. Neural networks are particularly useful for capturing complex relationships in structured data and can handle the high dimensionality introduced by onehot encoding.

Model Architecture: The model is structured with multiple hidden layers, optimized for classifying customers based on churn likelihood. Specific layer details, including activation functions and dropout rates, are set up to prevent overfitting and enhance generalization.

Training Process: The model is trained using the processed dataset, with evaluation metrics like accuracy, precision, and recall monitored during training to ensure the model accurately identifies potential churners.

A key aspect to remember is to save not only the trained model itself but also any preprocessing tools — such as scalers for structured data or vectorizers for NLP data — that were used to transform the data during training. By saving these preprocessing tools, we ensure that any data transformations applied to training data can be consistently reproduced when making predictions on new data. This consistency helps maintain model accuracy and reliability.

## Step 2: Integrating the ML Model with Fetch.ai Agents for Real-Time Predictions

In this section, we embed the saved ML model and preprocessing tools into a Fetch.ai agent that autonomously predicts customer churn. Let’s look at the code and how each part works.

## Code Walkthrough

1. Importing necessary libraries

import time from uagents import Agent, Context, Model from uagents.setup import fund_agent_if_low import pandas as pd from tensorflow.keras.models import load_model import joblib

2. Defining Data Models The CustomerDetails data model defines the fields received as input for prediction and the Notify data model defines the predicted outcome (churn) along with customer details.

class CustomerDetails(Model):

CreditScore: int Geography: str Gender: str Age: int Tenure: int Balance: int NumOfProducts: int HasCrCard: int IsActiveMember: int Complain: int SatisfactionScore: int

class Response(Model):

timestamp: int text: str agent_address: str

class Notify(Model):

churn: bool CreditScore: int Geography: str Gender: str Age: int Tenure: int Balance: int NumOfProducts: int HasCrCard: int IsActiveMember: int Complain: int SatisfactionScore: int

3. Initializing the Churn Prediction Agent

agent = Agent( name="Churn Prediction Agent", seed="churn-prediction-seed", port=8000, endpoint=["http://127.0.0.1:8000/submit"] )

fund_agent_if_low(agent.wallet.address())

4. Defining Notification agent address

customer_retention_agent_address= " "

5. Handling POST Requests and Preprocessing Data

This function, decorated to handle POST requests, receives customer data and prepares it for model input.

@agent.on_rest_post("/rest/post", CustomerDetails, Response) async def churn_prediction(ctx: Context, req: CustomerDetails) -> Response:

ctx.logger.info("Received Customer Details") customer_data = pd.DataFrame([{ 'CreditScore': req.CreditScore, 'Geography': req.Geography, 'Gender': req.Gender, 'Age': req.Age, 'Tenure': req.Tenure, 'Balance': req.Balance, 'NumOfProducts': req.NumOfProducts, 'HasCrCard': req.HasCrCard, 'IsActiveMember': req.IsActiveMember, 'Complain': req.Complain, 'Satisfaction Score': req.SatisfactionScore }])

a. Data Preprocessing: Follow the same data preprocessing steps as you did for model training to maintain consistency. (Refer the Jupyter Notebook)

customer_data['Gender'] = customer_data['Gender'].map({'Female': 1, 'Male': 0})

customer_data = pd.get_dummies(customer_data, columns= ['Geography'], drop_first=True) for col in ['Geography_Germany', 'Geography_Spain']:

if col not in customer_data.columns:

customer_data[col] = 0 column_order = ['CreditScore', 'Gender', 'Age', 'Tenure',

| 'Balance', | 'NumOfProducts','HasCrCard', | 'IsActiveMember', |
| --- | --- | --- |
| 'Complain', | 'Satisfaction | Score','Geography_Germany', |

'Geography_Spain']

customer_data = customer_data[column_order]

b. Loading the Pre-trained Scaler and Model

loaded_scaler = joblib.load('scaler.save') scaled_customer_data = pd.DataFrame(loaded_scaler.transform(customer_data), columns=customer_data.columns)

loaded_model_smot = load_model("model_smot.h5")

c. Predict if the customer intends to leave the bank

The model outputs a probability, which we interpret as a churn prediction if it exceeds a threshold.

smot_prediction = loaded_model_smot.predict(scaled_customer_data)

prediction = smot_prediction.flatten() >= 0.5

d. Collaborate with Customer Retention Agent to retain customers by sending customer details and churn prediction.

if prediction:

customer_details = Notify( churn=True, CreditScore=req.CreditScore, Geography=req.Geography, Gender=req.Gender, Age=req.Age, Tenure=req.Tenure, Balance=req.Balance, NumOfProducts=req.NumOfProducts, HasCrCard=req.HasCrCard, IsActiveMember=req.IsActiveMember, Complain=req.Complain, SatisfactionScore=req.SatisfactionScore )

await ctx.send(customer_retention_agent_address, customer_details)

return Response( text=f"Request has been processed", agent_address=ctx.agent.address, timestamp=int(time.time()), )

Code blocks a-d are a part of the churn_prediction function so make sure they are well intended.

3. Running the Agent if __name__ == "__main__": agent.run()

## Step 3: Taking an Action based on the Prediction

In this step, we’ll set up the Customer Retention Agent that receives customer churn notifications from the prediction agent, generates a personalized retention offer, and sends an SMS notification if necessary.

## Code Walkthrough

1. Importing necessary libraries

from uagents import Model, Context, Agent from uagents.setup import fund_agent_if_low import requests import json from requests.auth import HTTPBasicAuth from openai import OpenAI

2. Defining the Data Model: The Notify model describes the structure of incoming notifications from the prediction agent.

class Notify(Model):

churn: bool CreditScore: int Geography: str Gender: str Age: int Tenure: int Balance: int NumOfProducts: int HasCrCard: int IsActiveMember: int Complain: int SatisfactionScore: int

3. Initializing the Customer Retention Agent: Make sure both the agents are using different ports as they will be used for communication.

agent = Agent( name="customer-retention-agent", seed="customer-retention-agent-seed", port=8001, endpoint=f"http://localhost:8001/submit" )

fund_agent_if_low(agent.wallet.address())

4. Generating a Personalized Offer: This function takes customer details as input and uses OpenAI’s GPT-3.5 model to generate a custom retention message.

async def generate_an_offer(credit_score, geography, gender, age, tenure, balance, num_of_products, has_cr_card, is_active_member, complain, satisfaction_score):

prompt = f""" A bank customer is at risk of leaving the bank. Here are their details:

- Credit Score: {credit_score}

- Geography: {geography}

- Gender: {gender}

- Age: {age}

- Tenure with bank: {tenure} years

- Account Balance: ${balance}

- Number of Products: {num_of_products}

- Has Credit Card: {"Yes" if has_cr_card else "No"}

- Is Active Member: {"Yes" if is_active_member else "No"}

- Has a Complaint: {"Yes" if complain else "No"}

- Satisfaction Score: {satisfaction_score} (out of 5)

Based on this information, create a polite, engaging, and personalized message that the bank can send directly to this customer. The message should offer specific benefits or incentives that would be most appealing based on their profile, such as fee waivers, extra reward points, or special loyalty programs. The goal is to encourage the customer to stay with the bank.

"""

client = OpenAI() response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] )

offer_text = response.choices[0].message.content.strip() return offer_text

5. Sending Offers to Customers via SMS:

async def notify_family(message):

username = "xxxxxxxxxx" api_key = "xxxxxxxxxx"

url = 'https://rest.clicksend.com/v3/sms/send'

payload = { "messages": [ { "source": "python", "body": message, "to": "+44999999999", "from": "PythonApp"

} ] }

response = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'}, auth=HTTPBasicAuth(username, api_key))

if response.status_code == 200:

print('Message sent successfully!') print(response.json())

else:

print(f'Failed to send message. Status code: {response.status_code}')

print(response.json())

6. Print Agent Address on Startup: When you run the script you will see the agent address in terminal logs, copy this address and paste it in Churn-Prediction-Agent code.

@agent.on_event("startup") async def print_address(ctx: Context):

ctx.logger.info(agent.address)

7. Performing an action on receiving a message from Churn-Prediction-Agent:

@agent.on_message(model=Notify) async def send_message(ctx: Context, sender: str, msg: Notify):

ctx.logger.info(msg.churn) ctx.logger.info(msg.CreditScore)

offer_discounts = await generate_an_offer( msg.CreditScore, msg.Geography, msg.Gender, msg.Age, msg.Tenure, msg.Balance, msg.NumOfProducts, msg.HasCrCard, msg.IsActiveMember, msg.Complain, msg.SatisfactionScore )

print(offer_discounts)

await notify_family(offer_discounts)

The send_message function handles incoming Notify messages. When the prediction agent sends a Notify message, this function:

Logs the churn prediction and customer credit score. Generates a personalized retention offer using the generate_an_offer function. Sends an SMS notification with the offer details via the notify_family function.

7. Running the Agent

if __name__ == "__main__":

agent.run()

## Testing the system

1. Run the customer-retention-agent.py and copy the agent’s address from the logs (agent1qt5r492qwtpqa0v6nfugdw2lmpc8up02kyjw8y3wlshqqefzggsas85njw6) and paste it in churn-prediction-agent.py

(.venv) (base) kshipra@MacBook-Pro ML-hackathon-example % python3 customer-retention-agent.py WARNING: [customer-retention-agent]: Failed to register on Almanac API: ClientConnectorCertificateError

INFO: [customer-retention-agent]: Registering on almanac contract...

INFO: [customer-retention-agent]: Registering on almanac contract...complete

INFO: [customer-retention-agent]: agent1qt5r492qwtpqa0v6nfugdw2lmpc8up02kyjw8y3wlshqqefzggsas85njw6

INFO: [customer-retention-agent]: Agent inspector available at https://agentverse.ai/inspect/?

uri=http%3A//127.0.0.1%3A8001&address=agent1qt5r492qwtpqa0v6nfugdw2lmpc8up02kyjw8y3wlshqqefzg

INFO: [customer-retention-agent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)

2. Run the churn-prediction-agent.py in another terminal.

(.venv) (base) kshipra@MacBook-Pro ML-hackathon-example % python3 churn-prediction-agent.py WARNING: [Churn Prediction Agent]: Failed to register on Almanac API: ClientConnectorCertificateError

INFO: [Churn Prediction Agent]: Registering on almanac contract...

INFO: [Churn Prediction Agent]: Registering on almanac contract...complete

INFO: [Churn Prediction Agent]: Agent inspector available at https://agentverse.ai/inspect/?

uri=http%3A//127.0.0.1%3A8000&address=agent1q0qpc0u06d3m6ef2c9ezafths7pkkntsgyld55ccx2xtze3n3

INFO: [Churn Prediction Agent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)

3. Query the agent using the following curl command or build your own custom frontend. To test the application using the curl command open a third terminal and paste the following.

curl -d '{"CreditScore":619,"Geography":"France","Gender":"Female","Age":42,"Tenure":2,"Balance":0,"N \ -H "Content-Type: application/json" \ -X POST http://localhost:8000/rest/post

4. After executing the query, check the terminal where the churn-prediction-agent.py is running. It should display the prediction as a boolean value.

(.venv) (base) kshipra@MacBook-Pro ML-hackathon-example % python3 prediction-agent.py 2024-11-08 06:50:56.437293: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.

To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.

WARNING: [Churn Prediction Agent]: Failed to register on Almanac API: ClientConnectorCertificateError

INFO: [Churn Prediction Agent]: Almanac contract registration is up to date!

INFO: [Churn Prediction Agent]: Agent inspector available at https://agentverse.ai/inspect/?

uri=http%3A//127.0.0.1%3A8000&address=agent1q0qpc0u06d3m6ef2c9ezafths7pkkntsgyld55ccx2xtze3n3

INFO: [Churn Prediction Agent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)

| INFO: | [Churn Prediction Agent]: Received POST request |
| --- | --- |
| INFO: | [Churn Prediction Agent]: CreditScore Gender Age |

Tenure Balance NumOfProducts HasCrCard IsActiveMember Complain Satisfaction Score Geography_Germany Geography_Spain

| 0 | 619 | 1 42 | 2 | 0 | 1 |
| --- | --- | --- | --- | --- | --- |
| 1 | 1 | 1 | 2 | 0 |  |

0 WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 45ms/step

INFO: [Churn Prediction Agent]: SMOTE Model Prediction (Churn=1, No Churn=0):True

Next check the terminal where the customer retention agent is running. It should generate an offer and you should also receive a text message on the number you added while Customer Retention Agent creation.

(.venv) (base) kshipra@MacBook-Pro ML-hackathon-example % python3 customer-retention-agent.py WARNING: [customer-retention-agent]: Failed to register on Almanac API: ClientConnectorCertificateError

INFO: [customer-retention-agent]: Registering on almanac contract...

INFO: [customer-retention-agent]: Registering on almanac contract...complete

INFO: [customer-retention-agent]: agent1qt5r492qwtpqa0v6nfugdw2lmpc8up02kyjw8y3wlshqqefzggsas85njw6

INFO: [customer-retention-agent]: Agent inspector available at https:

INFO: [customer-retention-agent]: Starting server on http: INFO:httpx:HTTP Request: POST https:

Dear Sir/Ma'am,

We value your relationship with ABC Bank and appreciate your loyalty. We understand that you have a complaint and are not fully satisfied with your experience. As a gesture of goodwill, we would like to offer you fee waivers, extra reward points, and access to our exclusive loyalty programs. Our goal is to address your concerns and improve your overall satisfaction with our services. Please give us the opportunity to make things right and continue serving you as a valued customer.

Warm Regards, ABC Bank Message sent successfully! {'http_code': 200, 'response_code': 'SUCCESS', 'response_msg': 'Messages queued for delivery.', 'data': {'total_price': 0.1329, 'total_count': 1, 'queued_count': 1, 'messages': [{'direction': 'out', 'date': 1731048577, 'to': '+447469060527', 'body': "Dear Sir/Ma'am,\n\nWe value your relationship with ABC Bank and appreciate your loyalty. We understand that you have a complaint and are not fully satisfied with your experience. As a gesture of goodwill, we would like to offer you fee waivers, extra reward points, and access to our exclusive loyalty programs. Our goal is to address your concerns and improve your overall satisfaction with our services. Please give us the opportunity to make things right and continue serving you as a valued customer.\n\nWarm Regards,\nABC Bank", 'from': '+447908661619', 'schedule': 1731048577, 'message_id': '1EF9D9D9-ED70-6DD2-8FD1-85DE42632697', 'message_parts': 4, 'message_price': '0.1329', 'from_email': None, 'list_id': None, 'custom_string': '', 'contact_id': None,

'user_id': 549229, 'subaccount_id': 624300, 'is_shared_system_number': True, 'country': 'GB', 'carrier':

| 'Vodafone', | 'status': | 'SUCCESS'}], | '_currency': |
| --- | --- | --- | --- |
| {'currency_name_short': | 'GBP', | 'currency_prefix_d': | '£', |

'currency_prefix_c': 'p', 'currency_name_long': 'British Pounds'}, 'blocked_count': 0}}

Check out the full code in the GitHub repository for a complete implementation.

Integrating machine learning models with Fetch.ai Agents enables agents to make highly context-aware decisions while autonomously collaborating with other agents. This powerful combination allows for proactive, customer-centric actions, such as identifying and retaining at-risk customers through personalized outreach. Each agent operates independently yet synchronizes seamlessly with others, creating a network that improves operational efficiency in real-world applications.

Page 2

## Building a RAG-Based AI Agent for Dog Care with PREM and Fetch.ai

### In this article, we will explore how to build a RAG-based (Retrieval Augmented Generation) AI agent using PREM’s powerful tools and deploy…

Page 3

## Artificial Superintelligence Alliance Token Merge

### Fetch.ai is joining forces with SingularityNET and Ocean Protocol to create the Artificial Superintelligence Alliance. The token ticker for…

Page 4

## History of AI: Part IV — The Boom (80s)

### The 1980s stood out as a key era in Artificial Intelligence (AI). In these years, AI evolved from a field largely confined to academic…

Page 5

## Unlocking Innovation with Fetch.ai’s Agentverse

### In today’s fast-paced world, creating applications should be a seamless process, enabling innovators to bring their ideas to life without…

Page 6

## Agentic Mesh — Principles for an Autonomous Agent Ecosystem

### Foundational principles that let autonomous agents find each other, collaborate, interact, and transact in a growing Agentic Mesh…

## Harnessing Unsupervised Learning for Anomaly Detection in Legal Data

### Exploring AI’s Role in Transforming Legal Analysis by Uncovering Hidden Patterns and Ensuring Compliance.

Page 8

## Multi-Agent Systems: A Transformative Paradigm in AI

### One of the most promising and rapidly evolving areas within AI right now is the realm of multi-agent Systems (MAS) due to their potential…

Page 9

## OmniVision-968M: The World’s Most Compact and Smallest Multimodal Vision Language Model for Edge AI

### How OmniVision-968M Outperforms Existing Vision-Language Models and Enables Efficient AI on Resource-Constrained Devices

Page 10

## Python is No More The King of Data Science

### 5 Reasons Why Python is Losing Its Crown

Page 11

## MLOps — ML/DL Model Deployment

### Model deployment is the process of making machine learning model accessible to someone or something else.

chrome-extension://ecabifbgmdmgdllomnfinbmaellmclnh/data/reader/index.html?id=1147200348&url=https%3A%2F%2Fmedium.com%2Ffetch-ai%2Finteg… 10/10
