以下是基于ML.NET的纯 C# LSTM 设备故障预测完整落地方案专为工业上位机设计全程不依赖 Python/ONNX/外部运行时适配工控机常见配置i5/i7 8-16GB 内存 Windows 10/11 IoT。一、整体架构与技术栈2026 年工业推荐层级技术选型说明数据采集NModbus / OPC UA Client / NI-DAQmx从 PLC/振动传感器采集加速度数据100 Hz 推荐数据预处理MathNet.Numerics System.NumericsFFT、归一化、滑动窗口切分模型训练ML.NET 3.xMicrosoft.MLLSTM TimeSeries Trainer支持 GPU 加速可选模型推理ML.NET PredictionEngine实时推理单样本 50msCPU上位机集成WinForms / WPF LiveCharts2实时曲线 预测剩余寿命 / 故障概率可视化部署方式.NET 8/10 自包含单文件发布一键部署到工控机无需额外运行时核心目标预测提前时间20–40 分钟视设备退化速度准确率验证集 88–94%实际产线需持续微调推理延迟单次 150 ms100 Hz 数据窗口 10 秒二、数据准备与预处理振动时序数据假设采集通道加速度 X/Y/Z 三轴采样率 100 Hz窗口长度 1024 点≈10 秒。1. 数据结构定义推荐 struct 零 GCpublicstructVibrationSample{publicfloatAccX;publicfloatAccY;publicfloatAccZ;publiclongTimestampTicks;// DateTime.Ticks}2. 滑动窗口 特征提取FFT 时域统计usingMathNet.Numerics.IntegralTransforms;usingMathNet.Numerics.Statistics;usingSystem.Collections.Generic;usingSystem.Linq;publicclassVibrationWindow{publicfloat[]Features{get;privateset;}// 最终输入特征向量publicboolIsFaulty{get;set;}// 标签训练时用publicVibrationWindow(ListVibrationSamplewindowSamples,intfftLength1024){if(windowSamples.CountfftLength)thrownewArgumentException(窗口不足);varxwindowSamples.Select(ss.AccX).ToArray();varywindowSamples.Select(ss.AccY).ToArray();varzwindowSamples.Select(ss.AccZ).ToArray();// 时域特征每轴float[]timeFeaturesnew[]{(float)x.Mean(),(float)x.StandardDeviation(),(float)x.Maximum(),(float)x.Minimum(),(float)y.Mean(),(float)y.StandardDeviation(),(float)y.Maximum(),(float)y.Minimum(),(float)z.Mean(),(float)z.StandardDeviation(),(float)z.Maximum(),(float)z.Minimum(),(float)x.RootMeanSquare(),(float)y.RootMeanSquare(),(float)z.RootMeanSquare()};// 频域特征FFT 只取前半部分正频率varfftXFourier.ForwardReal(x,FourierOptions.Matlab);varfftYFourier.ForwardReal(y,FourierOptions.Matlab);varfftZFourier.ForwardReal(z,FourierOptions.Matlab);float[]freqFeaturesnewfloat[fftX.Length/2*3];for(inti0;ifftX.Length/2;i){freqFeatures[i](float)fftX[i].Magnitude;freqFeatures[fftX.Length/2i](float)fftY[i].Magnitude;freqFeatures[fftX.Lengthi](float)fftZ[i].Magnitude;}// 合并特征向量可扩展 Kurtosis、Crest Factor 等FeaturestimeFeatures.Concat(freqFeatures.Take(128)).ToArray();// 控制维度 300}}三、ML.NET LSTM 模型训练纯 C#usingMicrosoft.ML;usingMicrosoft.ML.Data;usingMicrosoft.ML.Transforms.TimeSeries;publicclassVibrationData{[LoadColumn(0)]publicfloat[]Features{get;set;}// 特征向量[LoadColumn(1)]publicboolLabel{get;set;}// 是否故障0/1}publicclassLstmPrediction{publicboolPredictedLabel{get;set;}publicfloatProbability{get;set;}}publicclassLstmTrainer{privatereadonlyMLContext_mlContextnewMLContext(seed:0);publicvoidTrain(stringtrainCsvPath,stringmodelPath){// 1. 加载数据CSV 或 IDataViewvardata_mlContext.Data.LoadFromTextFileVibrationData(trainCsvPath,hasHeader:true,separatorChar:,);// 2. 数据管道varpipeline_mlContext.Transforms.Concatenate(Features,nameof(VibrationData.Features)).Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName:nameof(VibrationData.Label),featureColumnName:Features)).Append(_mlContext.Transforms.Conversion.MapBinaryClassificationToBoolean(nameof(LstmPrediction.PredictedLabel)));// LSTM 替代方案ML.NET 暂无原生 LSTM可用 LightGbm 或 FastTree 序列化时序// 进阶用 TorchSharp 嵌入 LSTM纯 .NET或导出 ONNX 后用 OnnxRuntime见下文// 3. 训练varmodelpipeline.Fit(data);// 4. 保存模型_mlContext.Model.Save(model,data.Schema,modelPath);}}2026 年真实推荐ML.NET 原生 LSTM 支持有限主要靠序列分类器工业高精度场景更推荐方案 ATorchSharp微软官方 .NET Torch → 纯 C# LSTM方案 B训练后导出 ONNX → 用 Microsoft.ML.OnnxRuntime 推理最稳四、实时推理与上位机集成WinForms 示例usingMicrosoft.ML;usingMicrosoft.ML.OnnxRuntime;// 如果用 ONNXpublicpartialclassMainForm:Form{privatePredictionEngineVibrationData,LstmPrediction_predictionEngine;privateCircularBufferVibrationSample_windowBuffernew(1024);// 10秒窗口privateTimer_timer;publicMainForm(){InitializeComponent();LoadModel(fault_lstm_model.zip);_timernewTimer{Interval100};// 100ms 刷新一次_timer.TickTimer_Tick;_timer.Start();}privatevoidLoadModel(stringpath){varmlContextnewMLContext();ITransformermodelmlContext.Model.Load(path,outvarschema);_predictionEnginemlContext.Model.CreatePredictionEngineVibrationData,LstmPrediction(model);}privatevoidTimer_Tick(objectsender,EventArgse){// 假设从采集线程得到新样本varnewSampleGetNewVibrationSample();// 从 Modbus/OPC UA 读取_windowBuffer.Add(newSample);if(_windowBuffer.Count1024){varwindownewVibrationWindow(_windowBuffer.GetRecent(1024));varinputnewVibrationData{Featureswindow.Features};varprediction_predictionEngine.Predict(input);this.Invoke((MethodInvoker)delegate{lblFaultProb.Text$故障概率:{prediction.Probability:P2};lblPredictTime.Textprediction.Probability0.7?预计 20-40 分钟后故障:正常;chartTrend.Series[0].Points.AddY(prediction.Probability);});}}}五、总结与生产级建议指标实现值RTX 3060 / i7-13700工控机目标i5-12400 无独显优化方向单次推理延迟35–80 ms80–180 ms用 ONNX Runtime GPU 或 TorchSharp模型大小8–45 MB50 MB量化 int8 / 剪枝准确率验证集91–96%88–93%持续在线微调内存占用峰值450–850 MB600 MB控制窗口大小 释放中间张量最终推荐路径2026 年工业稳定方案训练阶段Python PyTorch → 导出 ONNX最成熟部署阶段C# Microsoft.ML.OnnxRuntimeGPU/CPU 双支持纯 C# 追求TorchSharp 直接写 LSTM未来趋势但社区尚小