图像分类和张量流服务

问题描述 投票:0回答:1

首先对不起我不是这个问题的准备,但我正在研究tensorflow服务以及如何投入生产我的cnn。真诚地,文件对我来说很困惑。我希望你能帮助更好地理解保存模型架构。所以请回复我作为老师,我想了解更多有关整个流程的信息。

我正在开发一个简单的cnn来将图像分类为4输出。我需要使用tensorflow服务才能投入生产。输入中的图像可以是小波束大小,CNN应该首先调整大小并进行预测。这里的代码

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot as plt
from scipy.misc import toimage
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import tag_constants, signature_constants, signature_def_utils_impl
import cv2



#train_path='Garage/train'
#train_datagen = ImageDataGenerator(rescale=1./255)
#train_batch = train_datagen.flow_from_directory(train_path, target_size=(64,64), class_mode='categorical', batch_size=10, color_mode='grayscale')


#validation_datagen = ImageDataGenerator(rescale=1./255)
#validation_batch = validation_datagen.flow_from_directory(
#        './Garage/validation',
#        target_size=(64, 64),
#        batch_size=3,
#        class_mode='categorical', color_mode='grayscale')

model = Sequential()
model.add(InputLayer(input_shape=[64,64,1]))
model.add(Conv2D(filters=32,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Conv2D(filters=50,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Conv2D(filters=80,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(4,activation='softmax'))
optimizer=Adam(lr=1e-3)

model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
#model.fit_generator(
#        train_batch,
#        epochs=50,
#        steps_per_epoch=6,
#        validation_data=validation_batch,
#        validation_steps=5)

model.load_weights('model.h5')

#score = model.evaluate_generator(validation_batch,steps=3)
#print('Test loss:', score[0])
#print('Test accuracy:', score[1])

#model.save('model.h5')


from PIL import Image
import requests
from io import BytesIO

response = requests.get('http://192.168.3.21:7451/shot.jpg')
image_pil = Image.open(BytesIO(response.content))
image = np.asarray(image_pil)

img2 = cv2.resize(image,(64,64))
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
img = np.reshape(img2,[1,64,64,1])

classes = model.predict_classes(img)

print(classes)

model_version="1"

sess = tf.Session()

#setting values for the sake of saving the model in the proper format
x = model.input
y = model.output

prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({"inputs":x}, {"prediction":y})

valid_prediction_signature = tf.saved_model.signature_def_utils.is_valid_signature(prediction_signature)
if(valid_prediction_signature == False):
    raise ValueError("Error: Prediction signature not valid!")

builder = saved_model_builder.SavedModelBuilder('./'+model_version)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')

# Add the meta_graph and the variables to the builder
builder.add_meta_graph_and_variables(
      sess, [tag_constants.SERVING],
      signature_def_map={
           signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:prediction_signature, },
      legacy_init_op=legacy_init_op)

# save the graph
builder.save()

代码将从凸轮http://192.168.3.21:7451/shot.jpg拍照,然后它将预测它

当我编译代码时,它在尝试保存模型时会返回很多错误。请你检查一下,告诉我保存模型说明是否正确?

我使用x = model.input作为服务的输入,但我希望它将图片作为服务器的输入。实际上我很困惑,抱歉。范围是当我请求gRPC预测图像时,模型可以给我预测结果谢谢

tensorflow-serving
1个回答
1
投票

我试着发表评论,因为我没有确定的答案,但我没有足够的空间。希望这些信息有用,可以通过“回答”。

无论如何,很难说像Tensorflow newb这样的问题是什么,没有看到任何错误。

我注意到的一件事是predict_signature_def()的方法调用似乎不遵循我在here找到的方法签名。

另外,我认为您不想使用您的模型所使用的相同代码进行图像下载/处理.TFServe不应该运行事后处理;只需托管您的模型。

所以你可以做的就是创建一个像你接受图像的RESTful服务,然后在它上面运行预处理,并将处理后的图像作为请求的一部分发送到TFServe。它看起来像这样:

user+image 
    -> requests classification to RESTful service 
    -> REST API receives image
    -> REST service resizes image
    -> REST service makes classification request to TFS (where your model is)
    -> TFS receives request, including resized/preprocessed image
    -> TFS invokes classification using your model and the arguments you sent
    -> TFS responds to REST service with model's response
    -> REST service responds to user with the classification from your model

这种情况很糟糕,因为在网络周围传递图像效率低,速度慢,但是当你找到痛点时可以进行优化。

主要思想是应将模型保存到可运行且不需要运行代码的工件/二进制文件中。这使您可以将建模与数据前后处理分开,并为您的模型提供更加一致的运行位置;例如您无需担心要运行的模型的竞争版本的依赖项。

缺点是它可能是一个学习曲线,以使这些部分在看起来像您拥有的单片架构之后很好地适应。

所以,在真正的Tensorflow知识出现真正的答案之前,我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.