Q:

Convert MobileNet from Keras to CoreML

I'm using Keras 2.1.3 and I want to convert MobileNet to CoreML:
from keras.applications import MobileNet
from keras.applications.mobilenet import relu6
from keras.applications.mobilenet import DepthwiseConv2D

import coremltools.converters.keras as k

def save_model():
    model = MobileNet(input_shape=(128,128,3), include_top=False)
    model.save('temp.h5')

def convert():
    model = k.convert('temp.h5',
                      input_names=['input'],
                      output_names=['output'],
                      model_precision='float16',
                      custom_conversion_functions={'relu6': relu6, 'DepthwiseConv2D': DepthwiseConv2D})
    model.save('temp.model')

save_model()
convert()

This gives an error: ValueError: Unknown activation function:relu6

A:

Here is solution based on https://github.com/apple/coremltools/issues/38
from keras.applications import MobileNet
import keras

import coremltools.converters.keras as k
from keras.utils.generic_utils import CustomObjectScope

def save_model():
    model = MobileNet(input_shape=(128,128,3), include_top=False)
    model.save('temp.h5')

def convert():
    with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6,
                            'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}):
        model = k.convert("temp.h5",
                          input_names=['input'],
                          output_names=['output'],
                          model_precision='float16')

    model.save('temp.mlmodel')

save_model()
convert()

