C# (.NET) 机器学习:库与工具概览

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

C# (.NET) 机器学习:关键库概览



尽管 Python 传统上被认为是机器学习 (ML) 的主要语言,但 C# (.NET) 生态系统提供了强大且成熟的解决方案,用于将 ML 模型集成到企业应用、Web 服务和桌面程序中。在本文中,我们将介绍 C# 开发人员可用的主要库、它们的功能、使用示例及应用场景。



1. ML.NET — 微软官方库



ML.NET 是微软开发的一个跨平台、开源且免费的机器学习库。它允许直接在 .NET 应用程序中创建、训练和使用 ML 模型,无需切换到 Python 或其他语言。



主要功能:

  • 支持经典算法:回归、分类、聚类、排序。
  • 通过集成 TensorFlow 和 ONNX 实现深度学习。
  • 自动机器学习 (AutoML) 用于选择最佳模型。
  • 内置数据处理管道(转换、归一化)。
  • 与 Visual Studio 集成(Model Builder 扩展)。


示例:二元分类(文本情感分析)

using Microsoft.ML;using Microsoft.ML.Data;

public class SentimentData{ public string SentimentText { get; set; } public bool Label { get; set; }}

public class SentimentPrediction{ public bool PredictedLabel { get; set; } public float Probability { get; set; }}

var context = new MLContext();// 加载数据IDataView data = context.Data.LoadFromTextFile<SentimentData>("data.tsv", separatorChar: '\\t');// 管道:文本特征化 + 训练var pipeline = context.Transforms.Text.FeaturizeText("Features", nameof(SentimentData.SentimentText)) .Append(context.BinaryClassification.Trainers.SdcaLogisticRegression());// 训练var model = pipeline.Fit(data);// 使用var engine = context.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(model);var prediction = engine.Predict(new SentimentData { SentimentText = "This is great!" });Console.WriteLine($"Predicted: {prediction.PredictedLabel}, Probability: {prediction.Probability}");


2. Accord.NET — 科学计算框架



Accord.NET 是一个强大的库,不仅提供 ML 算法,还提供信号处理、统计、计算机视觉和神经网络工具。它被认为是 .NET 最全面的解决方案之一。



主要功能:

  • 广泛的算法选择:SVM、随机森林、K-Means、朴素贝叶斯。
  • 深度神经网络 (Accord.Neuro)。
  • 图像和视频处理 (Accord.Imaging)。
  • 统计检验和分布。


示例:训练 SVM 分类器

using Accord.MachineLearning.VectorMachines;using Accord.MachineLearning.VectorMachines.Learning;using Accord.Statistics.Kernels;

// 训练数据(特征:两个数字)double[][] inputs = { new double[] { 0, 0 }, new double[] { 1, 1 }, new double[] { 1, 0 }, new double[] { 0, 1 }};int[] outputs = { 0, 1, 1, 0 };

// 创建并训练使用高斯核的 SVMvar teacher = new SequentialMinimalOptimization<Gaussian>(){ Complexity = 100};var svm = teacher.Learn(inputs, outputs);

// 预测int prediction = svm.Decide(new double[] { 0.8, 0.2 });Console.WriteLine($"Predicted class: {prediction}");


3. TensorFlow.NET — .NET 绑定到 TensorFlow



TensorFlow.NET (SciSharp) 是 TensorFlow 的官方低级 .NET 绑定。该库允许执行张量运算、构建和训练神经网络,以及加载

推荐