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 using SR-CNN
  • 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: SR-CNN (default in AnomalyML Library class), SSA, IsolationForest
  • Time-Series: SSA Forecasting, ARIMA
  • Classification: Binary & Multi-class
  • Regression: Linear, Poisson, FastTree
  • Clustering: K-Means, DBSCAN

Note: The built-in AnomalyML Library class uses the SR-CNN algorithm. Other algorithms are available through custom ML.NET pipelines built in Visual Studio.


Which ML Pattern Should I Use?

FrameworX supports three ML integration patterns. Choose the one that fits your use case:

PatternBest ForML Expertise NeededPage
AnomalyML Library ClassReal-time anomaly detection on live sensor data. Auto-trains from incoming data — no Visual Studio required.None[Skill Edge ML Pipeline](Skill Edge ML Pipeline) / [ML.NET Tutorial](ML.NET Tutorial)
Pre-trained Models (.zip)Multi-variable regression, classification, or anomaly detection using models trained offline in Visual Studio.Intermediate[ML.NET Pre-trained Models Example](ML.NET Example)
Model Builder (VS Extension)Visual Studio Model Builder extension generates ML code and trained models automatically from a dataset.Beginner-Intermediate[ML.NET Model Builder Example](ML.NET Model Builder Example)

Starting out? Use the AnomalyML Library Class. Import it in one click, wire it to your sensor tags, and anomaly detection starts working automatically after ~100 data points.


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](Scripts Classes Reference)

2. AI-Ready Architecture

FrameworX's event-driven architecture and consistent namespace provide the foundation for ML integration. The Unified Namespace, expression engine, and historian work together to feed sensor data into ML models and deliver predictions back to alarms and displays.

Learn more: [AI-Ready by Design](AI-Ready by Design)

3. Solution Examples

Pre-built examples demonstrate ML integration for industrial scenarios.

Learn more: [BottlingLine ML Demo](BottlingLine ML Demo)


Configuration Workflow

Step A: Import or Create ML Script Class

  1. Navigate to Scripts → Classes
  2. Click New and select Import from Library
  3. Choose AnomalyML
  4. Click OK

The AnomalyML class is self-contained pure .NET with no tag references. After import, the only customization needed is the sensitivity parameters at the top of the class:

// SENSITIVITY: SR-CNN detection parameters
// Adjust these after importing into your application.
// windowSize:          detection window (higher = less sensitive, more stable)
// threshold:           anomaly threshold (lower = more sensitive, more false positives)
// trainingBufferSize:  data points to collect before model trains
//                      At 5-second scan rate: 100 points = ~8 minutes warmup
// Defaults work well for most industrial processes at 1-5 second scan rates.
private int _windowSize = 32;
private double _threshold = 0.15;
private int _trainingBufferSize = 100;

AnomalyML Public Methods:

MethodReturnsDescription
Check(double)doubleFeed sensor value, returns anomaly score. Must execute first each cycle.
GetIsAnomaly()boolTrue if last Check() detected an anomaly
GetScore()doubleAnomaly severity from last Check() (0.0 = normal, 1.0 = severe)
GetBaseline()doubleExpected normal value from last Check()
IsModelReady()boolTrue after auto-training completes (~100 data points)
GetAnomalies()stringRecent anomaly history (also exposed as MCP Tool for AI queries)

Step B: Create ML Output Tags

Before wiring expressions, create tags to receive the model's predictions:

Tag NameTypeDescription
{Area}/ML/ScoreAnalogAnomaly score (0.0 to 1.0)
{Area}/ML/IsAnomalyDigitalTrue when anomaly detected
{Area}/ML/BaselineAnalogExpected normal value
{Area}/ML/ModelReadyDigitalTrue after training completes

Where {Area} is your UNS folder path (e.g., Brewery/BrewHouse, Plant/Reactor1).

Step C: Configure Expressions

Create expressions in Scripts → Expressions to wire the ML class to your tags:

ObjectNameExpressionTrigger
Tag.{Area}/ML/ScoreScript.Class.AnomalyML.Check(Tag.{Area}/{SensorTag})OnChange
Tag.{Area}/ML/IsAnomalyScript.Class.AnomalyML.GetIsAnomaly()OnChange
Tag.{Area}/ML/BaselineScript.Class.AnomalyML.GetBaseline()OnChange
Tag.{Area}/ML/ModelReadyScript.Class.AnomalyML.IsModelReady()OnChange

All four expressions should use the same TriggerTag (your sensor tag). The Score expression must execute first each cycle — it calls Check() which runs the ML model. The other three read results from that same prediction.

Important: After starting the runtime, the model needs ~100 data points to train. During warmup, Score will be 0 and ModelReady will be false. At a 5-second scan rate, expect ~8 minutes before predictions begin.

Multiple sensors: Each sensor needs its own class instance (e.g., AnomalyML_Temp, AnomalyML_Press) since one instance tracks one data stream. Import the Library class multiple times with different names.

For the complete step-by-step pipeline including alarms and displays, see the [Skill Edge ML Pipeline](Skill Edge ML Pipeline).


Deployment Patterns

Real-time Anomaly Detection

Monitor streaming sensor data for deviations using the AnomalyML Library class.

Tutorial: [How to Build an ML Model](ML.NET Tutorial)

The configuration workflow above (Steps A–C) is the complete setup for real-time anomaly detection. After wiring the expressions, create a Digital alarm on the IsAnomaly tag to notify operators when anomalies are detected:

  1. Navigate to Alarms → Items
  2. Create an alarm on Tag.{Area}/ML/IsAnomaly
  3. Set Type to Digital (triggers when IsAnomaly = true)

Predictive Maintenance

Forecast equipment failures using historical patterns. This pattern uses pre-trained models built in Visual Studio with multi-variable input features:

// Example: Pre-trained regression model loaded from .zip file
// See ML.NET Pre-trained Models Example for working implementation
public class MaintenanceML
{
    private PredictionEngine<EquipmentFeatures, FailurePrediction> engine;

    public void LoadModel(string modelPath)
    {
        var mlContext = new MLContext();
        var model = mlContext.Model.Load(modelPath, out var schema);
        engine = mlContext.Model.CreatePredictionEngine<EquipmentFeatures, FailurePrediction>(model);
    }

    public double PredictHoursToFailure(double temperature, double vibration, double runtime)
    {
        var features = new EquipmentFeatures
        {
            Temperature = (float)temperature,
            Vibration = (float)vibration,
            RuntimeHours = (float)runtime
        };
        return engine.Predict(features).HoursToFailure;
    }
}

Note: This pattern requires building and training a model externally in Visual Studio. See [ML.NET Pre-trained Models Example](ML.NET Example) for a working implementation.

Quality Prediction

Anticipate product quality based on process parameters. Like Predictive Maintenance, this uses pre-trained classification models:

// Example: Pre-trained classification model
// See ML.NET Pre-trained Models Example for working implementation
public class QualityML
{
    private PredictionEngine<ProcessFeatures, QualityPrediction> engine;

    public string PredictGrade(double temperature, double pressure, double speed)
    {
        var features = new ProcessFeatures
        {
            Temperature = (float)temperature,
            Pressure = (float)pressure,
            LineSpeed = (float)speed
        };
        return engine.Predict(features).QualityGrade; // A, B, C, etc.
    }
}

Note: This is an illustrative pattern. See [ML.NET Pre-trained Models Example](ML.NET Example) for a working multi-model implementation with Regression, Classification, and Anomaly Detection.


Complete Solution Example

BottlingLine ML Demo

A comprehensive example demonstrating ML integration in a bottling plant:

[BottlingLine ML Demo](BottlingLine ML Demo) — Complete IoT solution with:

  • Data collection from field devices
  • MQTT broker integration
  • SQLite historization
  • SR-CNN anomaly detection using AnomalyML Library class
  • 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)
  • Four-expression wiring pattern (Score, IsAnomaly, Baseline, ModelReady)

Getting Started

Quick Start Tutorial

Build your first ML model for anomaly detection:

[How to Build an ML Model](ML.NET Tutorial) — Step-by-step guide covering:

  • Value simulator setup
  • AnomalyML Library class import
  • ML output tag creation
  • Expression configuration (4-expression pattern)
  • Real-time testing and warmup behavior

Prerequisites

  1. Tags created in Unified Namespace
  2. Data source configured (simulator or real devices)
  3. Historian enabled (recommended for training data review, not required for AnomalyML auto-training)
  4. Script Classes module licensed

Best Practices

Model Training

  • AnomalyML auto-training — The Library class trains automatically from the first ~100 data points. No manual intervention needed.
  • Pre-trained models — Ensure sufficient historical data (minimum 1,000 samples). Use cross-validation on holdout datasets.
  • Feature Engineering — For multi-variable models, select relevant process variables that correlate with the target.
  • Regular Retraining — For pre-trained models, schedule periodic retraining to account for process drift. AnomalyML adapts continuously.

Performance Optimization

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

public ITransformer GetModel(string name)
{
    if (!ModelCache.TryGetValue(name, out var model))
    {
        model = mlContext.Model.Load($"Models/{name}.zip", out _);
        ModelCache[name] = model;
    }
    return model;
}

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

Note: The AnomalyML Library class handles its own model caching internally. These patterns apply to custom pre-trained model implementations.

Error Handling

public string SafePredict(double value)
{
    try
    {
        if (double.IsNaN(value) || double.IsInfinity(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 (pre-trained model pattern):

public class ModelManager
{
    private readonly MLContext mlContext = new();

    public ITransformer LoadModel(string version)
    {
        var path = $"Models/model_v{version}.zip";
        return mlContext.Model.Load(path, out var schema);
    }
}

Ensemble Methods

Combine multiple models for improved accuracy (advanced custom pattern):

public double EnsemblePredict(double value)
{
    var predictions = new[]
    {
        anomalyModel.Predict(value),
        spikeModel.Predict(value),
        changePointModel.Predict(value)
    };

    // Voting or averaging strategy
    return predictions.Average();
}

Note: Ensemble methods require building custom ML pipelines in Visual Studio. This is an advanced pattern not covered by the AnomalyML Library class.

Custom ML Pipelines

Create domain-specific ML workflows using the ML.NET API directly in Script Classes:

public ITransformer BuildCustomPipeline(IDataView trainingData)
{
    var mlContext = new MLContext();
    return mlContext.Transforms
        .NormalizeMinMax("Temperature")
        .Append(mlContext.Regression.Trainers.Sdca())
        .Fit(trainingData);
}

Note: Custom pipelines give full control over the ML.NET API but require ML expertise. For most anomaly detection use cases, the AnomalyML Library class is the recommended starting point.


Troubleshooting

Model not loading (pre-trained models)

  • Verify model .zip file path is correct and accessible at runtime
  • Check .NET runtime version compatibility
  • Ensure ML.NET NuGet assemblies are referenced in NamespaceDeclarations

AnomalyML not detecting anomalies

  • Check that ModelReady tag is true — if false, the model is still training (needs ~100 data points)
  • Verify sensor data is actually changing (flatline data won't trigger anomalies)
  • Adjust _threshold (lower = more sensitive) or _windowSize (lower = more reactive)
  • Confirm all four expressions are configured and the Score expression executes first

Poor prediction accuracy

  • Increase training data quantity (pre-trained models: minimum 1,000 samples)
  • Review feature selection — irrelevant variables add noise
  • Adjust model hyperparameters
  • Check for data drift (process has changed since training)

Performance issues

  • Cache trained models in memory (see Performance Optimization above)
  • Use batch predictions where possible for non-real-time analysis
  • Monitor memory usage with large models
  • The AnomalyML Library class is optimized for single-sensor real-time use

Integration errors

  • Verify Script Class build status (check for compile errors in Designer)
  • Check tag names and types match between expressions and UNS
  • Ensure expressions are configured with correct TriggerTag
  • Review runtime logs for exceptions: Monitor → Runtime Logs

ML.NET vs AI Runtime (LLM) Comparison

AspectML.NET IntegrationAI Runtime (LLM)
Output TypeDeterministicProbabilistic
Use CaseControl & MonitoringAssistance & Analysis
Response TimeMicrosecondsSeconds
TrainingRequired (auto or manual)Pre-trained
Consistency100% RepeatableVariable
Suitable for ControlYesNo
Runs OfflineYesRequires cloud/API

Both approaches complement each other. Use ML.NET for real-time control loops and alarms. Use AI Runtime for operator assistance, natural language queries, and solution analysis. See [AI Integration](AI Integration) for the full AI feature overview.


Related Documentation

  • [AI Integration](AI Integration) — Overview of all AI capabilities
  • [AI-Ready by Design](AI-Ready by Design) — Platform architecture for AI
  • [Scripts Classes Reference](Scripts Classes Reference) — Complete scripting documentation
  • [Skill Edge ML Pipeline](Skill Edge ML Pipeline) — AnomalyML step-by-step pipeline (AI skill)
  • [ML.NET Tutorial](ML.NET Tutorial) — Step-by-step tutorial on how to use an ML model
  • [ML.NET Pre-trained Models Example](ML.NET Example) — Pre-trained models from Visual Studio
  • [ML.NET Model Builder Example](ML.NET Model Builder Example) — Visual Studio Model Builder workflow
  • [BottlingLine ML Demo](BottlingLine ML Demo) — Complete solution example
  • [AI Runtime Connector](AI Runtime Connector) — LLM integration alternative
  • ML.NET Documentation: docs.microsoft.com/ml-net

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...