.Net机器学习入门

文章目录

安装包

powershell 复制代码
NuGet\Install-Package Microsoft.ML

用静态数据

Program.cs

csharp 复制代码
using Demo1;
using Microsoft.ML;

var context = new MLContext();
var modelPath = Path.Combine(AppContext.BaseDirectory, "model.zip");
var tools = new ModelTools
{
    Context = context,
    ModelPath = modelPath,
};
if (File.Exists(modelPath))
{
    tools.LoadModel();
}
else
{
    tools.TrainAndSave();
}

ModelTools.cs

csharp 复制代码
internal class ModelTools
{
    public MLContext Context { get; set; }
    public string ModelPath { get; set; }

    public void LoadModel()
    {
        // 加载已保存的模型
        Console.WriteLine($"📂 从 {ModelPath} 加载模型...");
        var model = Context.Model.Load(ModelPath, out var modelSchema);
        Console.WriteLine("✅ 模型加载成功!");

        // 使用模型进行预测
        UseModelForPrediction(model);
    }

    public void UseModelForPrediction(ITransformer model)
    {
        //创建预测引擎
        var predictionEngine = Context.Model.CreatePredictionEngine<IrisData, IrisPrediction>(model);

        //进行预测
        var sample = new IrisData
        {
            SepalLength = 5.1f,
            SepalWidth = 3.5f,
            PetalLength = 5.0f,
            PetalWidth = 2.0f
        };

        var prediction = predictionEngine.Predict(sample);

        Console.WriteLine("\n🔍 预测结果:");
        Console.WriteLine($"输入特征: 花萼长={sample.SepalLength}cm, 宽={sample.SepalWidth}cm");
        Console.WriteLine($"          花瓣长={sample.PetalLength}cm, 宽={sample.PetalWidth}cm");
        Console.WriteLine($"🌸 预测品种: {prediction.PredictedLabel}");
        Console.WriteLine($"🎯 实际品种: {sample.Label ?? "未知"}"); // 示例中未设置sample.Label
    }

    internal void TrainAndSave()
    {
        //训练数据
        var data = new[]
            {
                new IrisData { SepalLength=5.1f, SepalWidth=3.5f, PetalLength=1.4f, PetalWidth=0.2f, Label="Iris-setosa" },
                new IrisData { SepalLength=4.9f, SepalWidth=3.0f, PetalLength=1.4f, PetalWidth=0.2f, Label="Iris-setosa" },
                new IrisData { SepalLength=7.0f, SepalWidth=3.2f, PetalLength=4.7f, PetalWidth=1.4f, Label="Iris-versicolor" },
                new IrisData { SepalLength=6.4f, SepalWidth=3.2f, PetalLength=4.5f, PetalWidth=1.5f, Label="Iris-versicolor" },
                new IrisData { SepalLength=6.3f, SepalWidth=3.3f, PetalLength=6.0f, PetalWidth=2.5f, Label="Iris-virginica" },
                new IrisData { SepalLength=5.8f, SepalWidth=2.7f, PetalLength=5.1f, PetalWidth=1.9f, Label="Iris-virginica" }
            };
        //创建数据视图
        var dataView = Context.Data.LoadFromEnumerable(data);
        // 创建训练管道
        var pipeline = Context.Transforms.Conversion.MapValueToKey("LabelKey", "Label")
            .Append(Context.Transforms.Concatenate("Features",
                nameof(IrisData.SepalLength),
                nameof(IrisData.SepalWidth),
                nameof(IrisData.PetalLength),
                nameof(IrisData.PetalWidth)))
            .Append(Context.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelKey"))
            .Append(Context.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
        // 训练模型
        Console.WriteLine("⏳ 训练模型中...");
        var model = pipeline.Fit(dataView);
        Console.WriteLine("✅ 模型训练完成!");
        // 保存模型到文件
        Console.WriteLine($"💾 保存模型到: {ModelPath}");
        Context.Model.Save(model, dataView.Schema, ModelPath);
        Console.WriteLine("✅ 模型保存成功!");
        UseModelForPrediction(model);
    }
}

IrisData.cs

csharp 复制代码
public class IrisData
{
    [LoadColumn(0)] public float SepalLength; // 花萼长度
    [LoadColumn(1)] public float SepalWidth;  // 花萼宽度
    [LoadColumn(2)] public float PetalLength; // 花瓣长度
    [LoadColumn(3)] public float PetalWidth;  // 花瓣宽度
    [LoadColumn(4)] public string Label;      // 品种标签
}

public class IrisPrediction : IrisData
{
    public string PredictedLabel; // 预测结果
}

在这段代码中,Label就是我们要预测的「结论」(目标变量),而 SepalLength、SepalWidth、PetalLength、PetalWidth这四个属性是模型的「入参」(特征变量)。我们的训练就是总结特征变量和目标变量的相关性,从而在输入一个新的入参时预测结论。

相关推荐
机器之心11 分钟前
Generalist之后,罗剑岚团队推出LWD,也要变革具身智能训练范式
人工智能·openai
IT_陈寒15 分钟前
Vite的public文件夹放静态资源?这坑我替你踩了
前端·人工智能·后端
传说故事16 分钟前
【论文阅读】Diffusion Forcing: Next-token Prediction Meets Full-Sequence Diffusion
论文阅读·人工智能·diffusion
xixixi7777720 分钟前
三重筑基:5G-A超级上行提速千兆,电联低频共享扫平盲点,800V HVDC算电协同破局
人工智能·5g·ai·大模型·算力·通信·信通院
jkyy201421 分钟前
AI运动数字化:以技术重塑场景,健康有益赋能全域运动健康管理
大数据·人工智能·健康医疗
金融小师妹28 分钟前
4月30日多因子共振节点:鲍威尔“收官效应”与权力结构重塑的预期重构
大数据·人工智能·重构·逻辑回归
2601_9499251833 分钟前
AI Agent如何重构跨境物流的决策?
大数据·人工智能·重构·ai agent·geo优化·物流科技
AI木马人41 分钟前
1.人工智能实战:大模型推理接口响应慢?从模型加载到 FastAPI 部署的完整优化方案
人工智能·python·fastapi
Black蜡笔小新1 小时前
私有化本地化AI模型训推工作站DLTM训推一体工作站赋能多行业智能化落地
人工智能
qq_411262421 小时前
四博 AI 智能音箱 + ESPC3 Tasmota 计量通断器方案
人工智能·智能音箱