(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to detect machine failures with Azure ML and IoT sensors: step by step

João Barros 01 de September de 2026 4 min read

This tutorial shows how to detect machine failures using Azure AI & Machine Learning and IoT sensor data. The task is useful for predictive maintenance: predicting failures before they happen reduces costs and downtime.

Prerequisites

  • Azure account with permissions to create resources (Resource Group, Storage, Machine Learning workspace).
  • Azure Machine Learning workspace created.
  • IoT sensor dataset (CSV) with timestamps, readings and a failure label (0/1) or failure window.
  • Local Python 3.8+ with libraries: pandas, scikit-learn, azure-ai-ml (optional for deploy).

Step 1: Prepare sensor data and understand the objective

The objective is to transform time series from multiple sensors per machine into features that allow predicting a failure (binary classification). Start by loading the data, exploring missing values and ensuring a clear label: for example, the variable "failure" = 1 in the 24-hour window before the failure.

import pandas as pd
df = pd.read_csv('sensores.csv', parse_dates=['timestamp'])
# Exemplo de colunas: timestamp, machine_id, temp, vibration, pressure, failure
print(df.head())
print(df.isna().sum())

Step 2: Create temporal and aggregated features

Machines produce series: instead of using every point, aggregate by window (e.g., 1 hour) per machine. Compute mean, standard deviation, max, min and trend (slope) for each sensor. These features are more stable for traditional models like RandomForest.

import numpy as np
# Agrupar por janela de 1h
df = df.set_index('timestamp')
window = '1H'
agg = df.groupby('machine_id').resample(window).agg({
    'temp':['mean','std','min','max'],
    'vibration':['mean','std','min','max'],
    'pressure':['mean','std']
})
agg.columns = ['_'.join(col).strip() for col in agg.columns.values]
agg = agg.reset_index()
# Juntar label: se existir uma avaria nas próximas 24h
agg['failure_label'] = 0
# Aqui simplificamos: se algum failure==1 na próxima janela de 24h -> label=1
# Implementação real requer janelas deslocadas (lead time)

Step 3: Split train/validation and handle imbalance

Split datasets ensuring that machines in training may not appear in validation (avoids data leak). Failures are rare: apply oversampling (SMOTE) or class_weight in the model.

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
X = agg.drop(['machine_id','timestamp','failure_label'], axis=1)
y = agg['failure_label']
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

Step 4: Train a simple model and explain why

RandomForest works well as a baseline: it handles nonlinearities and does not require much tuning. Use class_weight='balanced' to handle imbalanced classes. Always validate with appropriate metrics (recall, F1) — in predictive maintenance recall is important to catch failures.

from sklearn.metrics import classification_report, confusion_matrix
model = RandomForestClassifier(n_estimators=100, class_weight='balanced', random_state=42)
model.fit(X_train.fillna(0), y_train)
pred = model.predict(X_val.fillna(0))
print(classification_report(y_val, pred))
print(confusion_matrix(y_val, pred))

Step 5: Interpretability and feature analysis

Knowing which features contribute most helps validate the model and build trust. Use the RandomForest feature_importances_ or SHAP for more detailed analyses.

importances = model.feature_importances_
feat_names = X_train.columns
imp_df = pd.DataFrame({'feature':feat_names,'importance':importances}).sort_values('importance',ascending=False)
print(imp_df.head(10))

Step 6: Prepare for deploy with Azure Machine Learning

Register the model in the Azure Machine Learning workspace and create an endpoint for real-time or batch predictions. The example uses azure-ai-ml for registration; the compute and endpoint configuration depends on your workspace.

from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential
from azure.ai.ml.entities import Model

credential = DefaultAzureCredential()
ml_client = MLClient(credential, subscription_id='SUA_SUBSCRIPTION', resource_group_name='RG', workspace_name='MLWorkspace')

# Guardar modelo localmente e registar
import joblib
joblib.dump(model, 'rf_model.joblib')
model_entity = Model(path='rf_model.joblib', name='rf_predictive_maintenance')
ml_client.models.create_or_update(model_entity)

Verify the outcome

Validate performance on the validation set: check metrics (recall, precision, F1) and the confusion matrix. In deployment, test the endpoint with example payloads (aggregated features) and confirm the response is plausible. Monitor prediction rates and feature drift.

Conclusion

You built a predictive maintenance pipeline: transformation of time series into features, training a baseline model, feature analysis and registration in Azure Machine Learning. Next steps: try time series models (LSTM, Transformers), real-time ingestion pipeline with IoT Hub and drift monitoring. Tip: start with simple windows and labels, then refine lead time and balancing according to results.