首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何序列化How分类器(serving_input_reciever)所需的张量输入

如何序列化How分类器(serving_input_reciever)所需的张量输入
EN

Stack Overflow用户
提问于 2018-06-21 17:22:33
回答 1查看 549关注 0票数 2

我希望能够在IIS之上使用tensorflowsharp来使用top分类器(估计器)。该模型之前已在python中进行过训练。到目前为止,我已经可以生成PB文件,知道正确的输入/输出,但是我在使用字符串输入时陷入了tensorflowsharp。

我可以创建一个有效的虹膜数据集的.pb文件。它使用以下feate_spec:

代码语言:javascript
复制
{'SepalLength': FixedLenFeature(shape=(1,), dtype=tf.float32, default_value=None), 'SepalWidth': FixedLenFeature(shape=(1,), dtype=tf.float32, default_value=None), 'PetalLength': FixedLenFeature(shape=(1,), dtype=tf.float32, default_value=None), 'PetalWidth': FixedLenFeature(shape=(1,), dtype=tf.float32, default_value=None)}

我已经创建了一个简单的c#控制台来尝试并启动它。输入应该是"input_example_tensor“,输出位于”dnn/input_example_tensor/predictions/probabilities“中。这是在alex_zu使用saved_model_cli命令here提供帮助后发现的。

据我所知,所有tensorflow估计器API的工作方式都是这样的。

问题来了: input_example_tensor应该是字符串格式,该格式将由ParseExample函数在内部解析。现在我被卡住了。我已经找到了TFTensor.CreateString,但这并不能解决问题。

代码语言:javascript
复制
using System;
using TensorFlow;

namespace repository
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TFGraph tfGraph = new TFGraph()){
                using (var tmpSess = new TFSession(tfGraph)){
                    using (var tfSessionOptions = new TFSessionOptions()){
                        using (var metaGraphUnused = new TFBuffer()){

                            //generating a new session based on the pb folder location with the tag serve
                            TFSession tfSession = tmpSess.FromSavedModel(
                                tfSessionOptions,
                                null,
                                @"path/to/model/pb", 
                                new[] { "serve" }, 
                                tfGraph, 
                                metaGraphUnused
                            );

                            //generating a new runner, which will fetch the tensorflow results later
                            var runner = tfSession.GetRunner();

                            //this is in the actual tensorflow documentation, how to implement this???
                            string fromTensorflowPythonExample = "{'SepalLength': [5.1, 5.9, 6.9],'SepalWidth': [3.3, 3.0, 3.1],'PetalLength': [1.7, 4.2, 5.4],'PetalWidth': [0.5, 1.5, 2.1],}";

                            //this is the problem, it's not working...
                            TFTensor rawInput = new TFTensor(new float[4]{5.1f,3.3f,1.7f,0.5f});
                            byte[] serializedTensor = System.Text.Encoding.ASCII.GetBytes(rawInput.ToString());
                            TFTensor inputTensor = TensorFlow.TFTensor.CreateString (serializedTensor);

                            runner.AddInput(tfGraph["input_example_tensor"][0], inputTensor);
                            runner.Fetch("dnn/head/predictions/probabilities", 0);

                            //start the run and get the results of the iris example
                            var output = runner.Run();
                            TFTensor result = output[0];

                            //printing response to the client
                            Console.WriteLine(result.ToString());
                            Console.ReadLine();
                        } 
                    }
                }
            }
        }
    }
}

此示例将显示以下错误:

代码语言:javascript
复制
An unhandled exception of type 'TensorFlow.TFException' occurred in TensorFlowSharp.dll: 'Expected serialized to be a vector, got shape: []
 [[Node: ParseExample/ParseExample = ParseExample[Ndense=4, Nsparse=0, Tdense=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], dense_shapes=[[1], [1], [1], [1]], sparse_types=[], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_input_example_tensor_0_0, ParseExample/ParseExample/names, ParseExample/ParseExample/dense_keys_0, ParseExample/ParseExample/dense_keys_1, ParseExample/ParseExample/dense_keys_2, ParseExample/ParseExample/dense_keys_3, ParseExample/Const, ParseExample/Const, ParseExample/Const, ParseExample/Const)]]'

我如何序列化张量,这样我才能正确使用pb文件?

我也在github上发布了这个问题,在这里你可以找到iris示例python文件,pb文件和控制台应用程序。在我看来,解决这个问题为所有拥有古老生产环境的tensorflow用户(像我)创建了一个整洁的解决方案。

EN

回答 1

Stack Overflow用户

发布于 2020-08-03 18:31:53

可以通过使用TFTensor.CreateString函数的重载来修复Expected serialized to be a vector, got shape: []错误:模型显然需要一个包含单个字符串的向量,而不是直接接受字符串:

代码语言:javascript
复制
TFTensor inputTensor = TFTensor.CreateString(new byte[][] { bytes }, new TFShape(1));

在本例中,input_example_tensor现在需要一个序列化的Example协议消息(另请参阅the docsthe example.proto文件)。

使用protobuf编译器,我已经生成了一个包含Example类的C#文件。你可以从这里下载:https://pastebin.com/iLT8MUdR。具体地说,我将此online toolCSharpProtoc一起使用,并将import "tensorflow/core/example/feature.proto";行替换为在that file中定义的消息。

将该文件添加到项目中后,您将需要一个对Google.Protobuf的包引用。然后,您可以将序列化示例传递给模型,如下所示:

代码语言:javascript
复制
Func<float, Tensorflow.Feature> makeFeature = (float x) => {
    var floatList = new Tensorflow.FloatList();
    floatList.Value.Add(x);
    return new Tensorflow.Feature { FloatList = floatList };
};

var example = new Tensorflow.Example { Features = new Tensorflow.Features() };
example.Features.Feature.Add("SepalLength", makeFeature(5.1f));
example.Features.Feature.Add("SepalWidth",  makeFeature(3.3f));
example.Features.Feature.Add("PetalLength", makeFeature(1.7f));
example.Features.Feature.Add("PetalWidth",  makeFeature(0.5f));

TFTensor inputTensor = TFTensor.CreateString(
    new [] { example.ToByteArray() }, new TFShape(1));

runner.AddInput(tfGraph["input_example_tensor"][0], inputTensor);
runner.Fetch("dnn/head/predictions/probabilities", 0);

//start the run and get the results of the iris example
var output = runner.Run();
TFTensor result = output[0];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50964956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档