Search code examples
kerascoremltoolsrelu

Core ML coremltools AttributeError: module 'keras.applications.mobilenet' has no attribute 'relu6'


We are trying to convert a .h5 Keras model into a .mlmodel model, my code is as follows:

from keras.models import load_model
import keras
from keras.applications import MobileNet
from keras.layers import DepthwiseConv2D

from keras.utils.generic_utils import CustomObjectScope

with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6,'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}):
    model = load_model('CNN_tourist_11.h5', custom_objects={'relu6': MobileNet})

output_labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

coreml_model = coremltools.converters.keras.convert("CNN_tourist_11.h5",
                                                    input_names="image",
                                                    image_input_names="image",
                                                    class_labels= output_labels,)

coremltools.utils.save_spec(coreml_model, 'place10.mlmodel')

We look up for the similiar question posed 6 days ago, and we also imported the MobileNet, but it still showing this error:

AttributeError: module 'keras.applications.mobilenet' has no attribute 'relu6'

My Tensorflow version is 1.10.0 and Keras version is 2.2.2

We will really appreciate if anyone can give us advice about why it keeps showing this error, thank you very much.


Solution

  • In latest Keras versions, MobileNet's components have been integrated with the rest of Keras' layers, so they are not available anymore as parts of the mobilenet package. Then you need to change the code to:

    from keras.models import load_model
    import keras
    from keras.applications import MobileNet
    from keras.layers import DepthwiseConv2D
    
    model = load_model('CNN_tourist_11.h5')
    
    output_labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    coreml_model = coremltools.converters.keras.convert("CNN_tourist_11.h5",
                                                        input_names="image",
                                                        image_input_names="image",
                                                        class_labels= output_labels,)
    
    coremltools.utils.save_spec(coreml_model, 'place10.mlmodel')