
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ML;
using Microsoft.ML.Data;
namespace MLApp
{
internal class Program
{
public class HouseData
{
public float Size { get; set; }
public float Price { get; set; }
}
public class Prediction
{
[ColumnName("Score")]
public float Price { get; set; }
}
static void Main(string[] args)
{
MLContext mlContext = new MLContext();
// 1. Import or create training data
HouseData[] houseData = {
new HouseData() { Size = 1.1F, Price = 1.2F },
new HouseData() { Size = 1.9F, Price = 2.3F },
new HouseData() { Size = 2.8F, Price = 3.0F },
new HouseData() { Size = 3.4F, Price = 3.7F } };
IDataView trainingData = mlContext.Data.LoadFromEnumerable(houseData);
// 2. Specify data preparation and model training pipeline
var pipeline = mlContext.Transforms.Concatenate("Features", new[] { "Size" }).Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "Price", maximumNumberOfIterations: 100));
// 3. Train model
var model = pipeline.Fit(trainingData);
// 保存模型
string modelPath = Path.Combine(Environment.CurrentDirectory, "TestModel.zip");
mlContext.Model.Save(model, trainingData.Schema, modelPath);
// 加载模型
ITransformer model_load = mlContext.Model.Load(modelPath, out var schema);
// 4. Make a prediction
var size = new HouseData() { Size = 2.5F };
// 方式1
var price = mlContext.Model.CreatePredictionEngine<HouseData, Prediction>(model).Predict(size);
// $作用是将{}内容当做表达式。 C 货币。
Console.WriteLine($" 直接预测 Predicted price for size: {size.Size * 1000} sq ft= {price.Price * 100:C}k");
// 方式2
var price_load = mlContext.Model.CreatePredictionEngine<HouseData, Prediction>(model_load).Predict(size);
// $作用是将{}内容当做表达式。 C 货币。
Console.WriteLine($" 加载模型预测 Predicted price for size: {size.Size * 1000} sq ft= {price_load.Price * 100:C}k");
// Predicted price for size: 2500 sq ft= $261.98k
// 等待用户按下任意键。避免窗口关闭。
Console.ReadKey();
}
}
}
