首页 > 解决方案 > ML.NET:如何将模型保存到数据库?

问题描述

我运行一个 ML.NET 示例应用程序,Program.cs 中有代码:...</p>

Console.WriteLine(“Training model…”);
var model = pipeline.Fit(trainTestData.TrainSet);

…即每次训练和创建模型时。问题:是否可以在模型训练和创建后将模型保存在数据库中,然后加载并重用保存的模型?它可以保存为 zip 文件并加载和重复使用。但是如何将其保存/加载到数据库中?

标签: ml.net

解决方案


模型可以保存为MemoryStream,然后转换为字节数组并存储在数据库中。

 using var memoryStream = new MemoryStream();

_mlContext.Model.Save(trainedModel, trainData.Schema, memoryStream);

_dbContext.Models.Add(new Model
{
    Data = stream.ToArray()
    // ...metadata
});

保存(流重载签名):

// Summary:
//     Save a transformer model and the loader used to create its input data to the
//     stream.
//
// Parameters:
//   model:
//     The trained model to be saved. Note that this can be null, as a shorthand for
//     an empty transformer chain. Upon loading with Microsoft.ML.ModelOperationsCatalog.LoadWithDataLoader(System.IO.Stream,Microsoft.ML.IDataLoader{Microsoft.ML.Data.IMultiStreamSource}@)
//     the returned value will be an empty Microsoft.ML.Data.TransformerChain`1.
//
//   loader:
//     The loader that was used to create data to train the model.
//
//   stream:
//     A writeable, seekable stream to save to.
public void Save<TSource>(ITransformer model, IDataLoader<TSource> loader, Stream stream)

推荐阅读