Muokkaa

Jaa


Make predictions with a trained model

Learn how to use a trained model to make predictions.

Create data models

Input data

public class HousingData
{
    [LoadColumn(0)]
    public float Size { get; set; }

    [LoadColumn(1, 3)]
    [VectorType(3)]
    public float[] HistoricalPrices { get; set; }

    [LoadColumn(4)]
    [ColumnName("Label")]
    public float CurrentPrice { get; set; }
}

Output data

Like the Features and Label input column names, ML.NET has default names for the predicted value columns produced by a model. The names can differ depending on the task.

Because the algorithm used in this sample is a linear regression algorithm, the default name of the output column is Score, which is defined by the ColumnName attribute on the PredictedPrice property.

class HousingPrediction
{
    [ColumnName("Score")]
    public float PredictedPrice { get; set; }
}

Set up a prediction pipeline

Whether making a single or batch prediction, the prediction pipeline needs to be loaded into the application. This pipeline contains both the data preprocessing transformations and the trained model. The following code snippet loads the prediction pipeline from a file named model.zip.

//Create MLContext
MLContext mlContext = new MLContext();

// Load Trained Model
DataViewSchema predictionPipelineSchema;
ITransformer predictionPipeline = mlContext.Model.Load("model.zip", out predictionPipelineSchema);

Single prediction

To make a single prediction, create a PredictionEngine using the loaded prediction pipeline.

// Create PredictionEngines
PredictionEngine<HousingData, HousingPrediction> predictionEngine = mlContext.Model.CreatePredictionEngine<HousingData, HousingPrediction>(predictionPipeline);

Then, use the Predict method and pass in your input data as a parameter. Notice that using the Predict method doesn't require the input to be an IDataView. That's because it conveniently internalizes the input data type manipulation so you can pass in an object of the input data type. Additionally, since CurrentPrice is the target or label you're trying to predict using new data, it's assumed there's no value for it at the moment.

// Input Data
HousingData inputData = new HousingData
{
    Size = 900f,
    HistoricalPrices = new float[] { 155000f, 190000f, 220000f }
};

// Get Prediction
HousingPrediction prediction = predictionEngine.Predict(inputData);

If you access the Score property of the prediction object, you should get a value similar to 150079.

Tip

PredictionEngine is not thread-safe. Additionally, you have to create an instance of it everywhere it is needed within your application. As your application grows, this process can become unmanageable. For improved performance and thread safety, use a combination of dependency injection and the PredictionEnginePool service, which creates an ObjectPool of PredictionEngine objects for use throughout your application.

For examples on how to use the PredictionEnginePool service, see deploy a model to a web API and deploy a model to Azure Functions.

For more information, see Dependency injection in ASP.NET Core.

Multiple predictions (IDataView)

Given the following data, load it into an IDataView. In this case, the name of the IDataView is inputData. Because CurrentPrice is the target or label you're trying to predict using new data, it's assumed there's no value for it at the moment.

// Actual data
HousingData[] housingData = new HousingData[]
{
    new HousingData
    {
        Size = 850f,
        HistoricalPrices = new float[] { 150000f, 175000f, 210000f }
    },
    new HousingData
    {
        Size = 900f,
        HistoricalPrices = new float[] { 155000f, 190000f, 220000f }
    },
    new HousingData
    {
        Size = 550f,
        HistoricalPrices = new float[] { 99000f, 98000f, 130000f }
    }
};

Then, use the Transform method to apply the data transformations and generate predictions.

// Predicted Data
IDataView predictions = predictionPipeline.Transform(inputData);

Inspect the predicted values by using the GetColumn method.

// Get Predictions
float[] scoreColumn = predictions.GetColumn<float>("Score").ToArray();

The predicted values in the score column should resemble the following values:

Observation Prediction
1 144638.2
2 150079.4
3 107789.8

Multiple predictions (PredictionEnginePool)

To make multiple predictions using PredictionEnginePool, you can take an IEnumerable containing multiple instances of your model input. For example, take an IEnumerable<HousingInput> and apply the Predict method to each element using the LINQ Select method.

This code sample assumes you have a PredictionEnginePool called predictionEnginePool and an IEnumerable<HousingData> called housingData.

IEnumerable<HousingPrediction> predictions = housingData.Select(input => predictionEnginePool.Predict(input));

The result is an IEnumerable containing instances of your predictions. In this case, it would be IEnumerable<HousingPrediction>.