我正在尝试使用在此code之后建模的Keras的Xception模型进行图像分类。但是,我想使用多个GPU使用此function进行批处理并行图像分类。我相信这是有可能的,并且我的原始代码可以在没有多GPU支持的情况下工作,但是我无法使multi_gpu_model函数正常工作。对于多GPU示例,我正在关注此example。这是我的代码(它是Flask应用程序的后端),它实例化模型,在创建类时对示例ndarray进行预测,然后在classify函数中期望使用base 64编码的图像:
import os
from keras.preprocessing import image as preprocess_image
from keras.applications import Xception
from keras.applications.inception_v3 import preprocess_input, decode_predictions
from keras.utils import multi_gpu_model
import numpy as np
import tensorflow as tf
import PIL.Image
from numpy import array
class ModelManager:
def __init__(self, model_path):
self.model_name = 'ImageNet'
self.model_version = '1.0'
self.batch_size = 32
height = 224
width = 224
num_classes = 1000
# self.model = tf.keras.models.load_model(os.path.join(model_path, 'ImageNetXception.h5'))
with tf.device('/cpu:0'):
model = Xception(weights=None,
input_shape=(height, width, 3),
classes=num_classes, include_top=True)
# Replicates the model on 8 GPUs.
# This assumes that your machine has 8 available GPUs.
self.parallel_model = multi_gpu_model(model, gpus=8)
self.parallel_model.compile(loss='categorical_crossentropy',
optimizer='rmsprop')
print("Loaded Xception model.")
x = np.empty((1, 224, 224, 3))
self.parallel_model.predict(x, batch_size=self.batch_size)
self.graph = tf.get_default_graph()
self.graph.finalize()
def classify(self, ids, images):
results = []
all_images = np.empty((0, 224, 224, 3))
# all_images = []
for image_id, image in zip(ids, images):
# This does the same as keras.preprocessing.image.load_img
image = image.convert('RGB')
image = image.resize((224, 224), PIL.Image.NEAREST)
x = preprocess_image.img_to_array(image)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
all_images = np.append(all_images, x, axis=0)
# all_images.append(x)
# a = array(all_images)
# print(type(a))
# print(a[0])
with self.graph.as_default():
preds = self.parallel_model.predict(all_images, batch_size=288)
#print(type(preds))
top3 = decode_predictions(preds, top=3)[0]
print(top3)
output = [((t[1],) + t[2:]) for t in top3]
predictions = [
{'label': label, 'probability': probability * 100.0}
for label, probability in output
]
results.append({
'id': 1,
'predictions': predictions
})
print(len(results))
return results
我不确定的部分是什么传递预测函数。目前,我正在对要分类的图像创建一个ndarray,对它们进行预处理,然后将其传递给预测函数。函数返回,但是preds变量不符合我的期望。我尝试遍历preds对象,但是当我传递单个项目时会发生errordecode_predictions错误,但是当我传递整个preds ndarray时会做出一个预测。在示例代码中,它们不使用decode_predictions函数,因此我不确定如何将其与parallel_model.predict的响应一起使用。谢谢您的帮助或资源。