Skip to content

Unable to successfully convert/run keras LSTM that uses batchsize>1 #303

Description

@lauriebyrum

It appears that batchsize>1 isn't currently supported in coreml with LSTMs. I haven't been able to find proof of this. If it is true, it means i need to break a single model into several as i have several LSTMs that all use batch. Please confirm if this is the case. If it isn't the case, then there is a bug somewhere. Here is the code that shows what I'm saying:
import keras
from keras.models import Sequential
import coremltools
import numpy as np

model = Sequential()
model.add(keras.layers.InputLayer(input_shape=(1, 1)))
bidir_layer = keras.layers.Bidirectional(keras.layers.LSTM(3, batch_size=2))
model.add(bidir_layer)
inputarray = np.array([[[1]],[[.5]]], dtype=np.float32)
keras_out = model.predict(inputarray)
coreml_model = coremltools.converters.keras.convert(model, input_names='input')
coreml_model.save('from_keras.mlmodel')

model = coremltools.models.MLModel('from_keras.mlmodel')

print("Both right answers from keras:" + str(keras_out))

predictions = model.predict({'input': inputarray[0][0]})
print("First right answer from coreml:" + str(predictions))
predictions = model.predict({'input': inputarray[1][0]})
print("Second right answer from coreml:" + str(predictions))

predictions = model.predict({'input':inputarray})
print("Wrong answer from coreml:" + str(predictions))
print(predictions)

Based on code in #147 (comment), the transpose below looks necessary, but it gives an error when predict is called:
Traceback (most recent call last):
File "keras-converter.py", line 32, in
predictions = model.predict({'input':inputarray})
File "lib/python3.6/site-packages/coremltools/models/model.py", line 326, in predict
return self.proxy.predict(data,useCPUOnly)
RuntimeError: {
NSLocalizedDescription = "Different batch numbers for input features.";
}
inputarray = np.transpose(inputarray, (1,0,2))
predictions = model.predict({'input':inputarray})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions