Buenas!
Hace unos días se libero la version 0.6.0 de Machine Learning .Net y una de las novedades mas importantes de la misma fue que la API de uso de ML.Net cambio de una forma muy importante. En mis sesiones siempre suelo comentar el escenario de predicción del Label de una persona para ver si es niño, bebe o adolescente de acuerdo con su edad y género. El set de datos con el que trabajo tiene la siguiente estructura
Como se puede ver en la imagen anterior, mi training data set posee las columnas Name, Age, Gender y Label. Pues bien, un detalle importante es que también necesito 2 clases con campos para representar las filas de mis trainings datasets y el resultado esperado.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AgeRangeData | |
{ | |
[Column(ordinal: "0")] | |
public float AgeStart; | |
[Column(ordinal: "1")] | |
public float AgeEnd; | |
[Column(ordinal: "2", name: "Label")] | |
public string Label; | |
} | |
public class AgeRangePrediction | |
{ | |
[ColumnName("PredictedLabel")] | |
public string PredictedLabels; | |
} |
Hasta la version 0.5.0 de ML.Net la forma de trabajo se basaba en crear un pipeline con los siguientes pasos
- Definir el modelo de datos y cargar los mismos
- Definir las Features y Labels
- Seleccionar un Trainer y entrenar el modelo
El modelo generado permitía realizar predicciones. El siguiente ejemplo lo explica en 20 líneas de código
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
var fileName = "AgeRanges.csv"; | |
var pipeline = new LearningPipeline(); | |
pipeline.Add(new TextLoader(fileName).CreateFrom<AgeRange>(separator: ',', useHeader: true)); | |
pipeline.Add(new Dictionarizer("Label")); | |
pipeline.Add(new ColumnConcatenator("Features", "Age")); | |
pipeline.Add(new StochasticDualCoordinateAscentClassifier()); | |
pipeline.Add(new PredictedLabelColumnOriginalValueConverter {PredictedLabelColumn = "PredictedLabel" }); | |
var model = pipeline.Train<AgeRange, AgeRangePrediction>(); | |
Predict(model, "john", 9, "M"); | |
Predict(model, "mary", 14, "M"); | |
Predict(model, "laura", 2, "M"); | |
Console.ReadLine(); | |
} |
Pues bien, con la version 0.6.0, la forma en la que se utiliza la API ha cambiado. Lo mejor en este punto es leer el post original de Cesar De la Torre donde explica las novedades de esta version (ver referencias). Sin embargo, creo que dejar un ejemplo del mismo código da una idea de lo flexible que es la nueva API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
var dataPath = "AgeRangeData.csv"; | |
var env = new LocalEnvironment(); | |
var reader = TextLoader.CreateReader(env, ctx => ( | |
Age: ctx.LoadFloat(1), | |
Label: ctx.LoadText(3)), | |
separator: ',', hasHeader: true); | |
var trainData = reader.Read(new MultiFileSource(dataPath)); | |
var classification = new MulticlassClassificationContext(env); | |
var learningPipeline = reader.MakeNewEstimator() | |
.Append(r => ( | |
r.Label, | |
Predictions: classification.Trainers.Sdca | |
(label: r.Label.ToKey(), | |
features: r.Age.AsVector()))) | |
.Append(r => r.Predictions.predictedLabel.ToValue()); | |
var model = learningPipeline.Fit(trainData); | |
var predictionFunc = model.AsDynamic.MakePredictionFunction<AgeRangeNewApi, AgeRangePredictionNewApi>(env); | |
var example = new AgeRangeNewApi() | |
{ | |
Age = 6, | |
Name = "John", | |
Gender = "M" | |
}; | |
var prediction = predictionFunc.Predict(example); | |
Console.WriteLine("prediction: " + prediction.PredictedLabel); | |
Console.ReadLine(); | |
} |
Los cambios principales los podemos encontrar en
- Líneas 5 a 9, carga del archivo inicial de datos para training
- Líneas 11 a 18, definición de Features y label para el training
- Línea 20, entrenamiento y creación del modelo
- Línea 22, creación de una función para realizar predicciones
- Líneas 24 a 32, ejemplo de una predicción
El ejemplo completo se puede ver aquí https://github.com/elbruno/Blog/tree/master/20181011%20MLNET%200.6%20NewAPI
Happy coding!
Saludos @ Toronto
El Bruno
References
My Posts
- Fix the error [System. InvalidOperationException, Entry Point ‘ Not found] when you train a pipeline
- Adding NuGet Packages in Preview mode from MyGet, ie: Microsoft.ML-0.6.0 Version
- ML.Net 0.5 initial support for TensorFlow
- New version 0.4, news Improvements in Text analysis using Word Embedding
- Error ‘Entry point ‘Trainers.LightGbmClassifier’ not found’ and how to fix it
- Machine Learning Glossary of terms
- Export Machine Learning.Net models to ONNX format
- Loading Data In our Learning Pipeline With List (Lists for ever!)
- What’s new in version 0.2.0
- What’s a Machine Learning model? A 7 minute video as the best possible explanation
- Write and Load models using Machine Learning .Net
- Understanding the step by step of Hello World
- Hello World in ML.Net, Machine Learning for .Net !
Interesante, yo escribo sobre modelos y análisis, mi último post es: https://diriangencuadra.com/2018/09/19/acabar-con-la-mina-de-oro-de-los-corruptos/
LikeLike