官术网_书友最值得收藏!

The Predictor class

The Predictor class, as noted earlier, is the class that provides prediction support in our project. The idea behind this method is to provide a simple interface to run the model, given the relatively simple input. In future chapters, we will be expanding this method structure to support more complex integrations, such as those hosted in a web application:

  1. Akin to what was done in the Trainer class, we verify that the model exists prior to reading it:
if (!File.Exists(ModelPath)) {
Console.WriteLine($"Failed to find model at {ModelPath}");

return;
}
  1. Then, we define the ITransformer object:
ITransformer mlModel;

using (var stream = new FileStream(ModelPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
mlModel = MlContext.Model.Load(stream, out _);
}

if (mlModel == null) {
Console.WriteLine("Failed to load model");

return;
}

This object will contain our model once we load via the Model.Load method. This method can also take a direct file path. However, the stream approach lends itself to support non on-disk approaches that we will use in later chapters.

  1. Next, create a PredictionEngine object given the model we loaded earlier:
var predictionEngine = MlContext.Model.CreatePredictionEngine<RestaurantFeedback,                        RestaurantPrediction>(mlModel);

We are passing in both TSrc and TDst, in our case for this project, RestaurantFeedback and RestaurantPrediction, respectively.

  1. Then, call the Predict method on the PredictionEngine class:
var prediction = predictionEngine.Predict(new RestaurantFeedback { Text = inputData });

Because, when we created the object with TSrc, the type was set to RestaurantFeedback, we have a strongly typed interface to our model. We then create the RestaurantFeedback object with the inputData variable that contains the string with the sentence we are going to run our model on.

  1. Finally, display the prediction output along with the probability: 
Console.WriteLine($"Based on \"{inputData}\", the feedback is predicted to be:{Environment.NewLine}" +
"{(prediction.Prediction ? "Negative" : "Positive")} at a {prediction.Probability:P0}" + " confidence");
主站蜘蛛池模板: 乌鲁木齐市| 巴青县| 泰顺县| 辽中县| 镇安县| 博野县| 临沂市| 玉田县| 满洲里市| 绵竹市| 鲁甸县| 虹口区| 扶绥县| 手机| 枣庄市| 玛纳斯县| 丰台区| 梅州市| 怀集县| 永胜县| 沭阳县| 武汉市| 德庆县| 滁州市| 云霄县| 鲁山县| 崇州市| 岳阳市| 沂源县| 集安市| 子长县| 喜德县| 新丰县| 赤峰市| 亚东县| 沈阳市| 东乡族自治县| 大宁县| 贺兰县| 汉川市| 江华|