Search code examples
swiftxcodecoremlswift5

How to solve CoreML - Failure verifying Inputs - Shape was not in enumerated set of allowed shape


Trying to integrate machine learning into a voice chat application. For now, the user can say, do two things - Accept or Reject based on voice input (converted to text using Apple Speech to Text APIs) To accept, the input could be Accept, Okay, Confirm etc and to reject, input could be Reject, No, Nope, I disagree etc.

I have a model which was built with Keras, and converted to mlmodel from a Tensorflow model format which I have integrated in my application.

The model takes MultiArray input and provides Array output.

A JSON file is used for training, which has parameters for an intent (eg - 'Accept' intent would have 'accept', 'okay', 'confirm' as parameters ). A Bag of words is created taking into account unique lowercased words across all parameters, and this size is used to create MLMultiArray from input string which is passed on to the predict method, as

let prediction = try! model.prediction(input1: mlMultiArray)

This gives an output of [(zero to one), (zero to one)] where the element at index 0 denotes Accept intent and element at index 1 denotes the possibility of Reject intent.

This works fine, if the json file has lesser number of parameters. For eg., when bag of words (no of unique words across all parameters) had 17 elements, the program ran fine. However when I added more parameters, and the bag of words now had 36 elements, I am getting an error Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=com.apple.CoreML Code=0 "Shape (36) was not in enumerated set of allowed shapes" UserInfo={NSLocalizedDescription=Shape (36) was not in enumerated set of allowed shapes}:

Using https://developer.apple.com/documentation/coreml/mlmultiarray/2879232-init this method to initialise the ML MultiArray


Solution

  • Core ML models expect the input to always be of a fixed size, say a vector of length 17.

    You can also use "size flexibility", which tells the model that it should expect inputs in a certain range, for example vectors between the lengths of 10 and 40 elements.

    It sounds like you need to configure your model to allow for size flexibility. You can use flexible_shape_utils from coremltools for this.