ML.NET 是一个跨平台的开源机器学习框架,专门为 开发者设计,允许在 .NET 应用程序中集成机器学习功能。如果你想在 .NET 应用中使用机器学习,ML.NET 是一个很好的选择。
第一步,老规矩,先安装
dotnet add package Microsoft.ML
ML.NET 通常需要数据集来进行训练和测试。假设有一个 CSV 文件,包含学生的学习时长和他们的考试成绩。我们将创建一个简单的模型,预测考试成绩。
data.csv
):StudyHours,Score
1,50
2,60
3,65
4,70
5,75
首先,定义一个数据类,表示 CSV 文件中的数据。
using Microsoft.ML.Data;
public class StudentData
{
[LoadColumn(0)]
public float StudyHours;
[LoadColumn(1)]
public float Score;
}
然后,定义一个预测结果类,表示模型输出的预测值。
public class StudentPrediction
{
public float Score;
}
在 Program.cs
中,我们将加载数据、构建一个简单的线性回归模型,并进行训练。
using System;
using Microsoft.ML;
using Microsoft.ML.Data;
using System.Linq;
var mlContext = new MLContext();
// 加载数据
var data = mlContext.Data.LoadFromTextFile<StudentData>("data.csv", separatorChar: ',', hasHeader: true);
// 分割数据为训练集和测试集
var trainTestSplit = mlContext.Data.TrainTestSplit(data, testFraction: 0.2);
// 构建数据处理管道(数据预处理)
var pipeline = mlContext.Transforms.Concatenate("Features", new[] { "StudyHours" })
.Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "Score", maximumNumberOfIterations: 100));
// 训练模型
var model = pipeline.Fit(trainTestSplit.TrainSet);
// 使用模型进行预测
var predictions = model.Transform(trainTestSplit.TestSet);
// 获取模型的评估指标
var metrics = mlContext.Regression.Evaluate(predictions, labelColumnName: "Score", scoreColumnName: "Score");
// 打印评估指标
Console.WriteLine($"R^2: {metrics.RSquared}");
Console.WriteLine($"Mean Absolute Error: {metrics.MeanAbsoluteError}");
Console.WriteLine($"Root Mean Squared Error: {metrics.RootMeanSquaredError}");
// 使用模型进行预测
var predictionFunction = mlContext.Model.CreatePredictionEngine<StudentData, StudentPrediction>(model);
var newStudent = new StudentData { StudyHours = 6 };
var predictedScore = predictionFunction.Predict(newStudent);
Console.WriteLine($"Predicted Score for 6 hours of study: {predictedScore.Score}");
运行项目, 将训练模型并预测一个学习了 6 小时的学生的考试成绩。
上面演示了如何使用 ML.NET 来构建一个机器学习模型。可以根据需要扩展这个示例,处理更多复杂的任务(例如分类、聚类、深度学习等)。
ML.NET 提供了许多有用的功能,包括:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有