我正在使用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);
}
答案 0 :(得分:2)
我认为您无需承担重担。尝试将其取下,看看是否可行。以下内容对我来说毫无问题。
ITransformer _model;
using (var stream = System.IO.File.OpenRead(modelPath))
{
_model = _context.Model.Load(stream);
}