Search code examples
kerascoremlcoremltools

Keras to CoreML value arror: list.remove(x): x not in list


Im trying to convert my Keras model (mobilenet + dence layers). The problem is that when I want to use coremltools for conversion I faced with the following problem:

Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-
packages/IPython/core/interactiveshell.py", line 3265, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-7905693382e5>", line 1, in <module>
    coreml_model = coremltools.converters.keras.convert(loaded_model)
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_keras_converter.py", line 752, in convert
    custom_conversion_functions=custom_conversion_functions)
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_keras_converter.py", line 550, in convertToSpec
    custom_objects=custom_objects)
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_keras2_converter.py", line 206, in _convert
    graph.build()
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_topology2.py", line 687, in build
    self._remove_old_edges(layer)
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_topology2.py", line 429, in _remove_old_edges
    self._remove_edge(layer, succ)
  File "/usr/local/lib/python3.6/dist-packages/coremltools/converters/keras/_topology2.py", line 365, in _remove_edge
    self.edge_map[src].remove(snk)
ValueError: list.remove(x): x not in list

Im trying to do this conversion by the following code:

js_file = open(args.ddir + args.mdl +'.json','r')
loaded_json_model = js_file.read()
js_file.close()

from keras.applications import mobilenet
from keras.utils.generic_utils import CustomObjectScope
from keras.models import model_from_json

with CustomObjectScope({'relu6': mobilenet.mobilenet.relu6}):
    loaded_model = model_from_json(loaded_json_model)
    loaded_model.load_weights(args.ddir + args.mdl + '.h5')

coreml_model = coremltools.converters.keras.convert(loaded_model,
                                                    input_names="image",
                                                    image_input_names="image"
                                                    )

Solution

  • I solved the problem by using proper version of the Keras which includes both Mobilenet (feature extractor) and at the same time "relu6". The only version (up to now) that worked for me is version "2.1.6". By this version I successfully did the conversion. coremltools does not supporting some layers for the moment (including relu6). This issue can be handled by "CustomObjectScope" an it was shown in the provided code. Note that, the network should be trained at this version (2.1.6) again.