c# - ML.NET 张量流 half_plus_two
问题描述
我正在尝试比较使用不同推理方法评估预构建张量流模型的性能。我目前half_plus_two
在 Ubuntu docker VM 中提供了 tensorflow 服务玩具模型,它产生以下结果:
GRPC:每秒约 1700 次预测
REST:每秒约 800 次预测
我的最终用途应用程序(带有 API 的框架 4.5)是一个 C# 环境。我想通过在我的最终使用应用程序中使用 ML.NET 预测/预测引擎来将 ML.NET 的性能与 tensorflow 服务的 REST 和 GRPC 进行比较。
环境
- 模型已经训练过了
- 推理是通过将单个浮点值输入模型然后处理返回的预测来完成的
- 最终用途应用程序将以每秒非常高的速率提供实时数据
- Tensorflow 2.x 创建模型并以
saved_model
格式保存
ML.NET 代码
class TestProgram
{
static void Main(string[] args)
{
try
{
new ModelBuilder();
}
catch (Exception e)
{
// investigate
}
}
}
public class ModelBuilder
{
private readonly MLContext mlContext;
private string userDesktop = Environment.SpecialFolder.Desktop.ToString();
// feed these values to the pretrained tf model.
// expected results are 2.0, 3.0, 4.0, 5.0 respectively
private float[] testData = new float[] { 0.0f, 2.0f, 4.0f, 6.0f };
public ModelBuilder()
{
this.mlContext = new MLContext();
var tfPretrainedModel = this.mlContext.Model.LoadTensorFlowModel(Path.Combine(userDesktop, @"TF\half_plus_two\1\saved_model.pb"));
var predictionFunction = this.mlContext.Model.CreatePredictionEngine<HalfPlusTwoData, HalfPlusTwoPrediction>(tfPretrainedModel);
HalfPlusTwoPrediction prediction = null;
for (int i = 0; i < this.testData.Length; i++)
{
prediction = predictionFunction.Predict(new HalfPlusTwoData() { Input = this.testData[i] });
Console.WriteLine($"Input {this.testData[i]}, Prediction {prediction.Prediction}, Expected {(this.testData[i] / 2) + 2}");
}
}
}
public class HalfPlusTwoData
{
[LoadColumn(0), ColumnName("Label")]
public float Input;
}
public class HalfPlusTwoPrediction
{
[ColumnName("PredictedLabel")]
public float Prediction { get; set; }
}
问题
LoadTensorFlowModel
1 使用创建模型或创建管道的正确方法是什么?- 2
HalfPlusTwoData
构造输入数据的正确方法是什么? - 3 'HalfPlusTwoPrediction' 是构建预测类的正确方法吗?
解决方案
阅读文档后,您应该TensorFlowModel
从该方法中获取一个对象。
微软文档:
TensorFlowModel tensorFlowModel = mlContext.Model.LoadTensorFlowModel(_modelPath);
至于你的 2 个课程,这就是这样做的方法。但是,您通常会有一些数据得到特征化,并且应该包含在第一类中。与您的预测类类似,它应该产生额外的列,例如分数和概率。尽管请注意,只有某些模型具有概率,例如二元分类模型。
MS Docs(情绪分析):
public class SentimentData
{
[LoadColumn(0)]
public string SentimentText;
[LoadColumn(1), ColumnName("Label")]
public bool Sentiment;
}
public class SentimentPrediction : SentimentData
{
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
public float Probability { get; set; }
public float Score { get; set; }
}
忽略它们具有不同的列号。这完全取决于您的数据是如何设置的。
链接:
涵盖输入和预测类布局:https ://docs.microsoft.com/en-us/dotnet/machine-learning/tutorials/sentiment-analysis
具体关于 TensorFlow 模型:https ://docs.microsoft.com/en-us/dotnet/machine-learning/tutorials/text-classification-tf
推荐阅读
- python - 如何将原始字符串转换为`bs4.element.Tag`
- c# - 如何隐藏滚动条仍在滚动?
- asp.net-core-mvc - asp-for 在幕后做了什么?
- javascript - Modal 在 Firefox 中有效,但在 Chrome 中无效
- regex - 正则表达式最多匹配 N 个数字,连字符和空格不受限制?
- gforth - 如何在 GForth 中保存程序/单词
- python - 基于Python中的某些值拆分列表?
- python - 在 PyMC3 中使用协变量构建 weibullAFT 模型?
- java - 在我的代码中查找安全漏洞 - LDAP 搜索
- javascript - 如何将 JavaScript url 链接到我的 index.php 页面