如何在c#中创建TensorProto

本文关键字:创建 TensorProto | 更新日期: 2023-09-27 18:11:55

这是我创建的c#客户端的一个片段,用于查询我使用本教程设置的tensorflow服务器:https://tensorflow.github.io/serving/serving_inception.html

        var channel = new Channel("TFServer:9000", ChannelCredentials.Insecure);
        var request = new PredictRequest();
        request.ModelSpec = new ModelSpec();
        request.ModelSpec.Name = "inception";
        var imgBuffer = File.ReadAllBytes(@"sample.jpg");
        ByteString jpeg = ByteString.CopyFrom(imgBuffer, 0, imgBuffer.Length);
        var jpgeproto = new TensorProto();
        jpgeproto.StringVal.Add(jpeg);
        jpgeproto.Dtype = DataType.DtStringRef;

        request.Inputs.Add("images", jpgeproto); // new TensorProto{TensorContent = jpeg});
        PredictionClient client = new PredictionClient(channel);

我发现大多数类需要使用protoc

从proto文件生成

我唯一找不到的是如何构建TensorProto。我一直得到的错误是:附加信息:状态(StatusCode=InvalidArgument, Detail="张量解析错误:图像")

有一个示例客户端(https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py),但我的Python技能不足以理解最后一位。

如何在c#中创建TensorProto

我还用另一种语言(Java)实现了该客户端。

尝试更改

jpgeproto.Dtype = DataType.DtStringRef; 

jpgeproto.Dtype = DataType.DtString;

你可能还需要在你的张量原型中添加一个具有维度的张量形状。这是我在Java中的工作解决方案,应该类似于c#:

TensorShapeProto.Dim dim = TensorShapeProto.Dim.newBuilder().setSize(1).build();
TensorShapeProto shape = TensorShapeProto.newBuilder().addDim(dim).build();
TensorProto proto = TensorProto.newBuilder()
                .addStringVal(ByteString.copyFrom(imageBytes))
                .setTensorShape(shape)
                .setDtype(DataType.DT_STRING)
                .build();
ModelSpec spec = ModelSpec.newBuilder().setName("inception").build();
PredictRequest r = PredictRequest.newBuilder()
                .setModelSpec(spec)
                .putInputs("images", proto).build();
PredictResponse response = blockingStub.predict(r);