coremltools: Keras mobilenet can't be imported (missing Relu6 / DepthwiseConv2D)

I have a custom trained MobileNet network from Keras and I bump into an issue about CoreML Tools not recognizing Relu6 as an activation function.

my keras model is something like:

import keras
from keras.layers.core import Flatten
initial_model = keras.applications.mobilenet.MobileNet(input_shape=(size, size, 3), include_top=False, weights='imagenet', classes=2)
last = initial_model.output
x = Flatten()(last)
preds = Dense(2, activation='softmax')(x)

model = Model(initial_model.input, preds)

And after training I try to convert it with:

from keras.utils.generic_utils import CustomObjectScope
with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6,'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}):
      convert = coremltools.converters.keras.convert("model.h5", input_names=['img'], image_input_names=['img'], class_labels=['class1', 'class2'])

But this raises:

RuntimeError: Unsupported option activation=relu6 in layer Dense(conv1_relu)

Because coreML Tools doesn’t know what DepthwiseConv2D and Relu6 are.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 24 (3 by maintainers)

Commits related to this issue

Most upvoted comments

If your keras is at “from tensorflow.python import keras” instead of at “import keras” then here is what worked for me:

from tensorflow.python.keras._impl.keras.utils.generic_utils import CustomObjectScope
from tensorflow.python.keras._impl.keras.applications import mobilenet
from tensorflow.python.keras._impl.keras.models import load_model
with CustomObjectScope({'relu6': mobilenet.relu6,'DepthwiseConv2D': mobilenet.DepthwiseConv2D}):
    model = load_model('weights.hdf5')

I suggest for conversion use Keras 2.1.6 to import relu6- import relu6 from “keras.applications.mobilenet”. the rest is just as I explained above. (tensorflow version does not matter)