🌐 简体中文 | 繁體中文 | Español | Deutsch | 日本語 | Français | Português | Русский | 한국어 | العربية
Machine learning for .NET: turn database tables and event streams into deployable models for classification, regression, multi-label, ranking, clustering, anomaly detection, forecasting and survival analysis — plus ONNX inference for external models, with a few lines of code.
Source: https://github.com/NewLifeX/NewLife.ML
NuGet: NewLife.ML · NewLife.ML.LightGbm · NewLife.ML.Onnx
dotnet add package NewLife.ML.LightGbmusing NewLife.ML;
using NewLife.ML.LightGbm;
// 1. Build a frame from any table: one column per feature, one column for the label
var frame = new MlFrame();
frame.AddColumn("Amount", amounts)
.AddColumn("Visits", visits)
.AddColumn("Churn", churn);
// 2. Train, then read metrics from the returned metadata
var trainer = new LightGbmTrainer();
var info = trainer.Train(frame, "Churn", new MlTrainerOptions
{
Task = MlTask.BinaryClassification,
ValidationRatio = 0.2,
});
var accuracy = info.Metrics["Accuracy"];
Console.WriteLine($"Features={String.Join(",", info.FeatureNames)} Accuracy={accuracy:F3}");
// 3. Score new rows, then persist the model as a single file
var sample = new MlFrame().AddColumn("Amount", [128.5]).AddColumn("Visits", [7]);
var prediction = trainer.Predict(sample);
Console.WriteLine($"Churn={prediction.Label} P={prediction.GetScore(1):F3}");
trainer.Model.Save("churn.model");
// 4. Reload in another process and keep predicting
var model = new LightGbmModel();
model.Load("churn.model");
var predictions = new LightGbmPredictor(model).PredictBatch(sample);- Nine task types, one contract: binary, multiclass and multi-label classification, regression, ranking, clustering, anomaly detection, forecasting and survival analysis share the same frame, trainer contract, model container and scoring entry point.
- Four steps, no pipeline plumbing: build a frame, train, score, save. No Schema, Estimator or Tensor in business code.
- Metadata travels with the model: feature names, label names, version and metrics are stored inside the model file, so a reloaded model is self-describing.
- Algorithm behind a contract:
IMlTrainerandIMlPredictorkeep LightGBM out of your code; swapping the engine does not touch callers. - Zero-dependency core:
NewLife.MLdepends only on NewLife.Core and runs from .NET Framework 4.6.1 up to .NET 11; native libraries live only in adapter packages. - Structured first, ONNX for the rest: tabular and time-series data is trained in-process; text, image, audio and deep models are reused through the ONNX adapter.
Data (4 items)
| Capability | What you get |
|---|---|
| Column-oriented frame | MlFrame stores one Double[] per column, matching how tables are read from databases and Excel |
| Column validation | Empty names, duplicate names and length mismatches fail fast instead of producing silent misalignment |
| Column access | GetColumn, TryGetColumn, GetColumnIndex, GetRow, ToArray |
| Label as a column | The label stays a normal column and is selected by name at training time |
Training (6 items)
| Capability | What you get |
|---|---|
| One training contract | IMlTrainer.Train(frame, labelColumn, options) returns metadata, not an opaque object |
| Binary classification | LightGBM boosted trees with calibrated probabilities |
| Multiclass classification | Per-class probability vector, class names supplied by the caller |
| Regression | Continuous target prediction with the same API shape |
| Reproducible split | Seeded validation split; set ratio to 0 to evaluate on the training set |
| Label guards | Binary labels must be 0/1, multiclass labels must be 0-based integers in range |
Evaluation (4 items)
| Capability | What you get |
|---|---|
| Classification metrics | Accuracy, precision, recall, F1 and a full confusion matrix |
| Binary AUC | Rank-based ROC area with tie handling |
| Regression metrics | MAE, MSE, RMSE and R² |
| Metrics in metadata | Results are written into MlModelInfo.Metrics with stable keys for reporting |
Model (4 items)
| Capability | What you get |
|---|---|
| Single-file model | Magic header + metadata JSON + model payload, copy the file and deploy |
| Stream and file access | Save(Stream), Load(Stream) plus path overloads |
| Self-describing metadata | Name, task, version, feature names, label names, creation time and metrics |
| Load consistency | Predictions after a save/load round trip match the in-memory model |
Scoring (4 items)
| Capability | What you get |
|---|---|
| Single-row scoring | Predict takes the first row of a frame |
| Batch scoring | PredictBatch keeps output order identical to input order |
| Structured results | MlPrediction carries scores, predicted label and regression value |
| Feature checks | Predictions validate feature columns against the model metadata before running |
Adapters (6 items)
| Capability | What you get |
|---|---|
| LightGBM package | NewLife.ML.LightGbm adds boosted-tree training for classification, regression, multi-label and ranking |
| ONNX inference | NewLife.ML.Onnx scores text, image, audio and deep models trained elsewhere |
| Entity mapping | Core MlEntityMapper turns entity or POCO lists into MlFrame and writes predictions back |
| Clean public API | No Microsoft.ML or ONNX type appears in public signatures |
| Runtime data view | MlFrame is adapted to IDataView with Boolean, Key or Single labels per task |
| Native isolation | LightGBM and ONNX native binaries are only pulled in by their adapter packages |
Capabilities (all delivered)
| Capability | What you get |
|---|---|
| Multi-label classification | One-vs-rest binary models with per-label thresholds and micro/macro metrics |
| Ranking | Pointwise learning-to-rank with grouped splits, NDCG@K and MAP |
| Clustering and PCA | KMeans, DBSCAN with noise flags, PCA with explained variance |
| Anomaly detection | Isolation forest, 3σ/IQR rules, spike/drop/drift detection and PR-AUC |
| Forecasting | Time-ordered splits, ARIMA(p,d,0), exponential smoothing, lag features and intervals |
| Feature engineering | Missing values, encodings, scaling, binning and WOE/IV, replayed with the model |
| Explainability | Permutation importance, partial dependence and occlusion contributions |
| Survival analysis | Cox PH with censoring, C-index and Kaplan-Meier curves |
| ONNX scoring | Reuse text, image, audio and deep models without training them in .NET |
| Entity mapping | Entity/POCO lists to MlFrame with predictions written back |
| Data access and profiling | DataTable, IDataReader and CSV import, type inference with automatic encoding, and a data health profile for missing values, outliers, duplicates and leakage |
| Training reliability | Random, stratified, grouped and time splits; sample and class weights; early stopping; baseline comparison; progress and cancellation; fingerprint verification; grid and random search |
| Evaluation and decisions | Probability calibration, threshold selection, ROC/PR/Lift/calibration curves, grouped metrics with confidence intervals, KS/Gini/Lift and regression intervals |
| Monitoring and governance | Feature and prediction drift (PSI/KS/Wasserstein), decay trends, model cards, model comparison, version index/compare/rollback and SHA256 file checks |
| Forecasting and delivery | Panel forecasting, STL decomposition, change points, ARIMA auto-order, residual intervals, counterfactual suggestions, scorecard export and LambdaRank |
NewLife is a layered ecosystem of independently versioned open-source projects. The map below is shared verbatim by every NewLife repository; each project links to its repository and its primary NuGet package.
| Project | What it does | Downloads |
|---|---|---|
| Foundation | ||
| NewLife.Core | Logging, configuration, caching, networking, serialization, scheduling and APM tracing. | |
| NewLife.XCode | Data middleware: single tables at the tens-of-billions scale, automatic sharding, read-write splitting, 10+ databases. | |
| NewLife.Net | High-performance network library: 1.77M pps / 14.5 Gbps on a single machine (TCP 1KB, 2026-10), 4M long-lived TCP connections. | |
| NewLife.Remoting | Protocol communication and RPC framework for client/server applications and IoT devices. | |
| NewLife.Agent | Installs .NET applications as OS daemons: Windows services and Linux systemd. | |
| NewLife.Templates | dotnet new project templates for console, web, API, service, data and IoT projects. |
|
| Data & Messaging | ||
| NewLife.Redis | Redis client with microsecond latency, millions of ops/s and built-in message queues. | |
| NewLife.RocketMQ | Pure managed RocketMQ client for Apache RocketMQ and Alibaba Cloud Message Queue. | |
| NewLife.MQTT | MQTT client and server, including Alibaba Cloud IoT connectivity. | |
| NewLife.NovaDb | Hybrid database in C#: embedded or networked, relational, time-series, message queue and KV in one. | |
| NewLife.MySql | MySql driver and helper layer built on the NewLife data stack. | |
| NewLife.TDengine | Pure managed TDengine ADO.NET driver with REST, WebSocket and native RPC transports, no native dependency. | |
| NewLife.Presto | Pure C# Presto/Trino ADO.NET driver with zero third-party dependencies and XCode ORM integration. | |
| Web & Distributed | ||
| NewLife.Cube | Rapid admin-platform framework: permissions, SSO, OAuth server and CRUD scaffolding. | |
| NewLife.Cube.React | Decoupled front-end sample for Cube: WebAPI backend with Swagger plus React, Vue and Blazor clients. | |
| Stardust | Distributed service platform: node management, APM, configuration center, registry and release center. | |
| AntJob | Distributed task and real-time data scheduling platform with sharding, retries and backfill. | |
| AI & Vision | ||
| NewLife.AI | Unified client for 46 LLM providers plus ChatAI, a ready-to-run web chat application. | |
| NewLife.Imaging | Pure managed imaging foundation: pixel model, codec contracts, drawing and metadata with zero native dependencies. | — |
| NewLife.Vision | Vision algorithms: OCR, barcodes, object detection and face recognition on top of NewLife.Imaging. | — |
| NewLife.ML | Tabular machine learning for .NET: turn database tables and Excel sheets into deployable prediction and classification models. | — |
| Industrial & IoT | ||
| NewLife.IoT | IoT standard library defining protocol contracts and device abstractions. | |
| NewLife.Modbus | Modbus TCP/RTU/ASCII implementation on top of NewLife.IoT. | |
| NewLife.Siemens | Siemens PLC protocol on top of NewLife.IoT. | |
| NewLife.Omron | Omron PLC protocol on top of NewLife.IoT. | |
| NewLife.Melsec | Mitsubishi Melsec PLC protocol on top of NewLife.IoT. | |
| NewLife.Schneider | Schneider PLC communication driver built on Modbus TCP. | |
| NewLife.OPC | OPC client for industrial data access. | — |
| NewLife.BACnet | BACnet building-automation protocol stack. | |
| NewLife.LoRa | LoRaWAN low-power wide-area protocol for long-range IoT connectivity. | |
| ZeroIoT | Lightweight open-source IoT platform with gateway and device management. | — |
| Vehicle Telematics | ||
| NewLife.JT808 | JT/T 808 vehicle positioning protocol: 70+ message bodies, 2011/2013/2019. | |
| NewLife.JT809 | JT/T 809 platform-to-platform protocol for transport authorities. | |
| NewLife.JT1078 | JT/T 1078 in-vehicle video: RTP parsing, FLV/fMP4 remuxing and live streaming. | |
| Domain Components | ||
| NewLife.Office | One package for Excel, Word, PPT, PDF and 15+ document formats. | |
| NewLife.Audio | Cross-platform audio: codecs, device I/O, DSP, containers and streaming. | |
| NewLife.Video | Video codecs, container formats, frame processing and streaming. | |
| NewLife.Map | Unified interface over Baidu, AMap, Tencent and Tianditu with geocoding and coordinate conversion. | |
| NewLife.IP | IPv4 geolocation with an offline memory-mapped database and an online API fallback. | |
| NewLife.Holiday | Chinese holiday and adjusted-workday identification library with built-in annual data and lunar festival support, fully offline. | |
| Tools & Products | ||
| CrazyCoder | Developer toolbox: network, serial port, crypto, regex, Modbus and MQTT. | |
| NewLife.UnitTest | Unit test extensions: test base classes, data-driven tests and dependency-injection helpers. | |
| GitCandy | Self-hosted Git source code management system. | — |
| LuckyClover | Installs the matching .NET runtime automatically when launched from an older host. | — |
Badges show the primary package of each project; theme, extension and satellite packages are listed on their NuGet pages. The 30+ packages not listed here (FTP, Office extensions, protocol drivers and more) are available under the NewLifeX organization and on newlifex.com.
| Document | Description |
|---|---|
| Requirements | Vision, goals and module breakdown |
| Model Landscape | Tasks, algorithms, adoption decisions and ONNX scenarios |
| Feature List | Features tracked across implementation, testing and comments |
| Architecture | Layers, training and scoring flows, design decisions |
| Competitive Analysis | Comparison with ML.NET, Accord.NET, SharpLearning, LightGBM bindings, ONNX Runtime and cross-language baselines |
| Change Log | Release history |
| MLDemo | Runnable sample: synthetic iris classification and linear regression |
dotnet build -c Release
dotnet test -c Release
dotnet pack -c Release -o outPull requests are welcome. Read Architecture before changing the core contracts, and keep third-party types out of public APIs.
Founded in 2002, the NewLife team has spent more than two decades on the .NET and IoT ecosystem, maintains nearly 100 open-source projects, and delivers integrated software and hardware solutions for power, logistics, healthcare, industrial control and internet industries.
Website: https://newlifex.com · Open source organization: https://github.com/NewLifeX
MIT License