public static void PredictWithModelLoadedFromFile(MLContext mlContext)
{
IEnumerable<SentimentData> sentiments = new[]
{
new SentimentData
{
SentimentText = "1、完成爱车年卡代码编写 2、与客户完成需求对接"
},
new SentimentData
{
SentimentText = "没有工作内容"
}
};
ITransformer loadedModel;
using (var stream = new FileStream(_modelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
loadedModel = mlContext.Model.Load(stream);
}
// 创建预测(也称之为创建预测房屋)
var sentimentStreamingDataView = mlContext.Data.ReadFromEnumerable(sentiments);
var predictions = loadedModel.Transform(sentimentStreamingDataView);
// 使用模型预测结果值为1(不合格)还是0 (合格)
var predictedResults = mlContext.CreateEnumerable<SentimentPrediction>(predictions, reuseRowObject: false);
Console.WriteLine();
Console.WriteLine("=============== 多样本加载模型的预测试验 ===============");
var sentimentsAndPredictions = sentiments.Zip(predictedResults, (sentiment, prediction) => (sentiment, prediction));
foreach (var item in sentimentsAndPredictions)
{
Console.WriteLine($"日报内容: {item.sentiment.SentimentText} | 是否合格: {(Convert.ToBoolean(item.prediction.Prediction) ? "合格" : "不合格")} | 符合率: {item.prediction.Probability} ");
}
Console.WriteLine("=============== 预测结束 ===============");
Console.ReadLine();
}
在以上的方法定义完成之后开始进行方法的调用:
public static void Main(string[] args)
{
//创建一个MLContext,为ML作业提供一个上下文
MLContext mlContext = new MLContext(seed: 0);
//初始化_textLoader以将其重复应用于所需要的数据集
_textLoader = mlContext.Data.CreateTextLoader(
columns: new TextLoader.Column[]
{
new TextLoader.Column("Label", DataKind.Bool,0),
new TextLoader.Column("SentimentText", DataKind.Text,1)
},
separatorChar: 't',
hasHeader: true
);
//定型模型
var model = Train(mlContext, _trainDataPath);
//评测模型
Evaluate(mlContext, model);
//单个数据预测
Predict(mlContext, model);
//批处理预测数据
PredictWithModelLoadedFromFile(mlContext);
}
准备代码之后,你的小小的机器人就要开始学习啦,好吧开始编译运行吧。。。。。。
运行产生结果为:










