ios / CoreML - 当keras模型转换为CoreML时,输入类型为MultiArray

时间:2017-07-06 18:54:09

标签: ios keras conv-neural-network cvpixelbuffer coreml

我正在尝试培训keras模型,并使用coreMLkeras 1.2.2后端将其转换为TensorFlow模型。这是一个分类任务。 CoreML的输入显示为MultiArray。我需要Image <BGR, 32, 32>CVPixelBuffer之类的内容。我尝试按照here添加image_input_names='data'。另外我的input shape(height, width, depth),我认为这是必需的。

请帮助解决此问题。我使用了cifar10数据集和以下代码(Reference):

from keras.datasets import cifar10
from keras.models import Model
from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten
from keras.utils import np_utils
import numpy as np
import coremltools

np.random.seed(1234)

batch_size = 32
num_epochs = 1

kernel_size = 3 
pool_size = 2 
conv_depth_1 = 32 
conv_depth_2 = 64 
drop_prob_1 = 0.25
drop_prob_2 = 0.5
hidden_size = 512 

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
num_train, height, width, depth = X_train.shape
num_test = X_test.shape[0]
num_classes = 10

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= np.max(X_train)
X_test /= np.max(X_test)

y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)

data = Input(shape=(height, width, depth))
conv_1 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(data)
conv_2 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(conv_1)
pool_1 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_2)
drop_1 = Dropout(drop_prob_1)(pool_1)

conv_3 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(drop_1)
conv_4 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(conv_3)
pool_2 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_4)
drop_2 = Dropout(drop_prob_1)(pool_2)

flat = Flatten()(drop_2)
hidden = Dense(hidden_size, activation='relu')(flat)
drop_3 = Dropout(drop_prob_2)(hidden)
out = Dense(num_classes, activation='softmax')(drop_3)

model = Model(inputs=data, outputs=out) 

model.compile(loss='categorical_crossentropy', 
              optimizer='adam', 
              metrics=['accuracy']) 

model.fit(X_train, y_train,                
          batch_size=batch_size, epochs=num_epochs,
          verbose=1, validation_split=0.1) 
loss, accuracy = model.evaluate(X_test, y_test, verbose=1)
print ("\nTest Loss: {loss} and Test Accuracy: {acc}\n".format(loss = loss, acc = accuracy))
coreml_model = coremltools.converters.keras.convert(model, input_names='data', image_input_names='data')
coreml_model.save('my_model.mlmodel')

2 个答案:

答案 0 :(得分:1)

我刚刚使用Keras 2检查了此信息,您的模型输入为Image<RGB,32,32>,而不是MultiArray。也许这取决于Keras版本。

如果您需要BGR,请将is_bgr=True添加到coremltools.converters.keras.convert()来电。

Here is the documentation此转换器。

答案 1 :(得分:0)

问题在于我的tf版本和protobuf版本。我能够通过安装coremltools`documentation中提到的版本来解决问题。