Deploy deterministic machine learning models for industrial automation with ML.NET integration

  • Name: ML.NET
  • Version: 1.0.0.1
  • Protocol: n/a
  • Interface: n/a
  • Runtime: .NET 2.0 (Multiplatform)
  • Configuration:
    • Scripts / Tasks


Overview

The AI ML Integration Connector brings deterministic machine learning capabilities to FrameworX solutions through ML.NET, Microsoft's cross-platform machine learning framework. Unlike probabilistic LLMs, this connector provides consistent, repeatable results suitable for real-time industrial control and monitoring applications.

Key Capabilities

  • Deterministic Predictions - Consistent outputs for identical inputs, essential for industrial processes
  • Real-time Anomaly Detection - Identify deviations in sensor data as they occur
  • Predictive Maintenance - Forecast equipment failures before they happen
  • Quality Prediction - Anticipate product quality based on process parameters
  • Time-Series Analysis - Pattern recognition in historical and streaming data

Integration Architecture

Industrial Data → FrameworX Tags → ML Models → Predictions
                        ↓                ↑
                   [Historian]      [ML.NET Engine]
                        ↓                ↑
                   [Training]       [Inference]

Technical Specifications

PropertyValue
NameML.NET Integration
FrameworkML.NET 3.0+
Runtime.NET 8.0
Model TypesClassification, Regression, Anomaly Detection, Time-Series
ConfigurationScripts → Classes
ExecutionReal-time & Batch

Supported ML Algorithms

  • Anomaly Detection: SSA, SrCNN, IsolationForest
  • Time-Series: SSA Forecasting, ARIMA
  • Classification: Binary & Multi-class
  • Regression: Linear, Poisson, FastTree
  • Clustering: K-Means, DBSCAN

Implementation Components

1. ML Script Classes

Create specialized script classes that implement ML.NET models for real-time inference and training.

Learn more: Scripts Classes Reference

2. AI-Ready Architecture

FrameworX's event-driven architecture and consistent namespace provide the foundation for ML integration.

Learn more: AI-Ready by Design

3. Solution Examples

Pre-built examples demonstrate ML integration for industrial scenarios.

Learn more: BottlingLine ML Demo


Configuration Workflow

Step 1: Create ML Script Class

  1. Navigate to Scripts → Classes
  2. Click New and select Import from Library
  3. Choose an ML template (e.g., AnomalyML)
  4. Customize the model parameters:

csharp

public class AnomalyML
{
    private SSAChangePointDetector detector;
    private Queue<double> dataBuffer = new Queue<double>(100);
    
    public string Check(double value)
    {
        dataBuffer.Enqueue(value);
        
        // Detect anomalies using SSA algorithm
        var prediction = detector.Predict(value);
        
        if (prediction.IsAnomaly)
        {
            @Info.Trace($"Anomaly detected: {value}");
            @Tag.AnomalyBuffer[0] = $"Alert: {value:F2}";
        }
        
        return prediction.Score.ToString();
    }
}

Step 2: Configure Real-time Monitoring

Create expressions to trigger ML inference on tag changes:

ObjectNameExpressionExecution

Script.Class.AnomalyML.Check(Tag.Pressure)OnChange

Script.Class.QualityML.Predict(Tag.Temperature)OnChange

Step 3: Train and Deploy Models

csharp

// Training method in ML Script Class
public void TrainModel()
{
    // Get historical data
    var data = @Historian.GetValues("Temperature", 10000);
    
    // Create ML pipeline
    var pipeline = mlContext.AnomalyDetection
        .DetectSpikeBySsa(
            outputColumnName: "Prediction",
            inputColumnName: "Value",
            confidence: 95,
            pvalueHistoryLength: 100,
            trainingWindowSize: 500,
            seasonalityWindowSize: 50);
    
    // Train model
    var model = pipeline.Fit(data);
    
    // Save trained model
    mlContext.Model.Save(model, dataSchema, "anomaly_model.zip");
}

Deployment Patterns

Real-time Anomaly Detection

Monitor streaming sensor data for deviations:

Tutorial: How to Build an ML Model

csharp

[OnTagChange("Tag.Pressure")]
public void MonitorPressure(double value)
{
    var result = Script.Class.AnomalyML.Check(value);
    if (result.IsAnomaly)
    {
        @Alarm.Create("PressureAnomaly", value);
    }
}

Predictive Maintenance

Forecast equipment failures using historical patterns:

csharp

public double PredictTimeToFailure(string equipmentId)
{
    var features = new EquipmentFeatures
    {
        Temperature = @Tag[$"{equipmentId}_Temp"],
        Vibration = @Tag[$"{equipmentId}_Vib"],
        Runtime = @Tag[$"{equipmentId}_Hours"]
    };
    
    return maintenanceModel.Predict(features).HoursToFailure;
}

Quality Prediction

Anticipate product quality from process parameters:

csharp

public string PredictQuality(ProcessParameters parameters)
{
    var prediction = qualityModel.Predict(parameters);
    return prediction.QualityGrade; // A, B, C, etc.
}

Complete Solution Example

BottlingLine ML Demo

A comprehensive example demonstrating ML integration in a bottling plant:

BottlingLine ML Demo - Complete IoT solution with:

  • Data collection from field devices
  • MQTT broker integration
  • SQLite historization
  • Anomaly detection models
  • Real-time dashboard visualization

Key Features Demonstrated

  • Value simulator for testing
  • MQTT publishing to cloud
  • ML anomaly detection on production metrics
  • Multi-platform displays (desktop/mobile/tablet)

Getting Started

Quick Start Tutorial

Build your first ML model for anomaly detection:

How to Build an ML Model - Step-by-step guide covering:

  • Value simulator setup
  • ML script class creation
  • Expression configuration
  • Real-time testing

Prerequisites

  1. Tags created in Unified Namespace
  2. Data source configured (simulator or real devices)
  3. Historian enabled for training data
  4. Script Classes module licensed

Best Practices

Model Training

  • Data Quality - Ensure sufficient historical data (minimum 1000 samples)
  • Feature Engineering - Select relevant process variables
  • Cross-validation - Test models on holdout datasets
  • Regular Retraining - Schedule periodic model updates

Performance Optimization

csharp

// Cache models in memory
private static readonly Dictionary<string, ITransformer> ModelCache = new();

// Use async processing for non-critical predictions
public async Task<double> PredictAsync(double[] features)
{
    return await Task.Run(() => model.Predict(features));
}

// Batch predictions when possible
public double[] BatchPredict(double[][] featureSets)
{
    return model.Transform(featureSets).GetColumn<double>("Score");
}

Error Handling

csharp

public string SafePredict(double value)
{
    try
    {
        if (!IsValidInput(value))
            return "Invalid Input";
            
        var prediction = model.Predict(value);
        
        @Info.Trace($"ML Prediction: {prediction}");
        return prediction.ToString();
    }
    catch (Exception ex)
    {
        @Alarm.Create("ML_Error", ex.Message);
        return "Prediction Error";
    }
}

Advanced Features

Model Versioning

Track and manage multiple model versions:

csharp

public class ModelManager
{
    public void LoadModel(string version)
    {
        var path = $"Models/model_v{version}.zip";
        currentModel = mlContext.Model.Load(path, out var schema);
    }
    
    public void CompareModels(string v1, string v2)
    {
        // A/B testing between model versions
    }
}

Ensemble Methods

Combine multiple models for improved accuracy:

csharp

public double EnsemblePredict(double value)
{
    var predictions = new[]
    {
        anomalyModel.Predict(value),
        spikeModel.Predict(value),
        changePointModel.Predict(value)
    };
    
    // Voting or averaging strategy
    return predictions.Average();
}

Custom ML Pipelines

Create domain-specific ML workflows:

csharp

public ITransformer BuildCustomPipeline()
{
    return mlContext.Transforms
        .NormalizeMinMax("Temperature")
        .Append(mlContext.Transforms.CalculateFeatures())
        .Append(mlContext.Regression.Trainers.Sdca())
        .Fit(trainingData);
}

Troubleshooting

Model not loading

  • Verify model file path is correct
  • Check .NET runtime version compatibility
  • Ensure ML.NET assemblies are referenced

Poor prediction accuracy

  • Increase training data quantity
  • Review feature selection
  • Adjust model hyperparameters
  • Check for data drift

Performance issues

  • Cache trained models in memory
  • Use batch predictions where possible
  • Consider async processing for non-critical paths
  • Monitor memory usage with large models

Integration errors

  • Verify Script Class build status
  • Check tag names and types match
  • Ensure expressions are configured correctly
  • Review runtime logs for exceptions

ML.NET vs MCP Tools Comparison

AspectML.NET IntegrationMCP Tools
Output TypeDeterministicProbabilistic
Use CaseControl & MonitoringAssistance & Analysis
Response TimeMicrosecondsSeconds
TrainingRequiredPre-trained
Consistency100% RepeatableVariable
Suitable for ControlYesNo

Related Documentation


The AI ML Integration Connector provides industrial-grade machine learning capabilities that maintain the determinism and reliability required for automation systems, while enabling advanced analytics and predictive capabilities that improve operational efficiency.


In this section...