如何在 ML.NET 中加载保存的模型?
How do you load a saved model in ML.NET?
我正在使用 ML.NET v0.11.0 创建和保存模型。保存过程似乎有效,但我很难确定如何重新加载该模型以供使用。
MLContext mlContext = new MLContext();
IDataView trainingDataView = mlContext.Data.LoadFromEnumerable(myData);
// Setup and train the model
var pipeline = mlContext.Transforms.Conversion.MapValueToKey("Label")
.Append(mlContext.Transforms.Concatenate("Features", "Field1", "Field2"))
.AppendCacheCheckpoint(mlContext)
.Append(mlContext.MulticlassClassification.Trainers.StochasticDualCoordinateAscent(labelColumnName: "Label", featureColumnName: "Features"))
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
var m = pipeline.Fit(trainingDataView);
using (var stream = System.IO.File.Create("mymodel.zip"))
{
// this works
mlContext.Model.Save(m, stream);
}
TransformerChain<KeyToValueMappingTransformer> loadedModel;
using (var stream = System.IO.File.OpenRead("mymodel.zip"))
{
// this will not work, as ITransformer cannot be cast to TransformerChain<KeyToValueMappingTransformer>
loadedModel = (TransformerChain<KeyToValueMappingTransformer>)mlContext.Model.Load(stream);
}
我认为你不需要施压。试着把它取下来,看看它是否有效。以下对我来说没有问题。
ITransformer _model;
using (var stream = System.IO.File.OpenRead(modelPath))
{
_model = _context.Model.Load(stream);
}
我正在使用 ML.NET v0.11.0 创建和保存模型。保存过程似乎有效,但我很难确定如何重新加载该模型以供使用。
MLContext mlContext = new MLContext();
IDataView trainingDataView = mlContext.Data.LoadFromEnumerable(myData);
// Setup and train the model
var pipeline = mlContext.Transforms.Conversion.MapValueToKey("Label")
.Append(mlContext.Transforms.Concatenate("Features", "Field1", "Field2"))
.AppendCacheCheckpoint(mlContext)
.Append(mlContext.MulticlassClassification.Trainers.StochasticDualCoordinateAscent(labelColumnName: "Label", featureColumnName: "Features"))
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
var m = pipeline.Fit(trainingDataView);
using (var stream = System.IO.File.Create("mymodel.zip"))
{
// this works
mlContext.Model.Save(m, stream);
}
TransformerChain<KeyToValueMappingTransformer> loadedModel;
using (var stream = System.IO.File.OpenRead("mymodel.zip"))
{
// this will not work, as ITransformer cannot be cast to TransformerChain<KeyToValueMappingTransformer>
loadedModel = (TransformerChain<KeyToValueMappingTransformer>)mlContext.Model.Load(stream);
}
我认为你不需要施压。试着把它取下来,看看它是否有效。以下对我来说没有问题。
ITransformer _model;
using (var stream = System.IO.File.OpenRead(modelPath))
{
_model = _context.Model.Load(stream);
}