Search code examples
swiftnumpypytorchcoreml

Convert from .npy to MLMultiArray for CoreML prediction in swift


I have exported a PyTorch model to CoreML and want to do inference in swift. I have my input data stored on disk as a 2D float32 numpy ndarray .npy and need load into a MLMultiArray in swift. Is there a convenient way to do this?


Solution

  • Instead of saving as .npy (which is pickled), save the raw data from NumPy:

    array.astype(np.float32).tofile(filename)
    

    Now you can simply load this into a Data object in Swift and copy that into the MLMultiArray.