TensorFlow服务:将图像传递到分类器

时间:2018-07-31 08:05:25

标签: python tensorflow tensorflow-serving

我在Tensorflow中构建了一个简单的分类器(Python,tensorflow 1.9.0和tensorflow-serving 1.9.0),该分类器将对象分为5个类之一。现在,我想为那个模型服务。我已经导出了它并给它一个分类签名(并且只有分类签名):

classification_signature = tf.saved_model.signature_def_utils.build_signature_def(
    inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs},
    outputs={
        signature_constants.CLASSIFY_OUTPUT_CLASSES:
            classification_outputs_classes
    },
    method_name=signature_constants.CLASSIFY_METHOD_NAME)

该行的下一行变为:

builder.add_meta_graph_and_variables(
            sess, [tag_constants.SERVING],
            signature_def_map={
                'classification_results':
                    classification_signature
            },
            clear_devices=True, legacy_init_op=legacy_init_op)

当我启动TF服务器时,我可以看到正在提供模型。我的问题是如何将图像从客户端传递到。代码如下:

request = classification_pb2.ClassificationRequest()
request.model_spec.name = model
request.model_spec.signature_name = 'classification_results' 

这就是我有点迷茫和困惑的地方。对于PredictionRequest,代码为:

request.inputs['inputs'].CopyFrom(
    tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1, height, width, 3]))

,但不适用于分类请求。错误是:

File "TestServices.py", line 99, in make_request
  request.inputs['inputs'].CopyFrom(
     AttributeError: 'ClassificationRequest' object has no attribute 'inputs'

都不:

request.input.CopyFrom(input_pb2.Input(
    tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1, height, width, 3])
    )
)

出现错误:

File "TestServices.py", line 102, in make_request
  tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1,height, width, 3])
    TypeError: Parameter to CopyFrom() must be instance of same class: 
    expected tensorflow.serving.Input got tensorflow.TensorProto.

因此,我的问题是:使用分类请求将图像传递给分类器需要做什么?

1 个答案:

答案 0 :(得分:0)

我不确定这是否符合最佳做法,但这似乎可行。作为纯粹的python用户,我不得不说这听起来像疯子。我花了一段时间,但通过查看protobuf文件的definition和这个documentation找到了答案。

Public Function PictureLookup(Value As String, Location As Range, Index As Integer)

Application.Volatile

Dim lookupPicture As Shape
Dim sheetName As String
Dim picTop As Double
Dim picLeft As Double

sheetName = Location.Parent.Name

'Delete current picture with the same Index if exists
For Each lookupPicture In Sheets(sheetName).Shapes
    If lookupPicture.Name = "PictureLookup" & Index Then
        lookupPicture.Delete
    End If
Next lookupPicture

'Get position of cell calling the UDF
picTop = Location.Top
picLeft = Location.Left

'Add the picture in the right location
Set lookupPicture = Sheets(sheetName).Shapes.AddPicture _
("G:\My Drive\MY FOLDER\LOGOS\" & Value & ".jpg", msoFalse, msoTrue, picLeft, picTop, -1, -1)

'change the picture name
lookupPicture.Name = "PictureLookup" & Index

PictureLookup = ""

End Function