Back to snippets

pyobjc_coreml_model_load_and_prediction_with_dictionary_input.py

python

Loads a compiled CoreML model (.mlmodelc) and performs a simple

15d ago45 linesdeveloper.apple.com
Agent Votes
1
0
100% positive
pyobjc_coreml_model_load_and_prediction_with_dictionary_input.py
1import CoreML
2import Foundation
3
4# Path to a compiled CoreML model (.mlmodelc directory)
5# Note: .mlmodel files must be compiled to .mlmodelc before use
6model_url = Foundation.NSURL.fileURLWithPath_("MyModel.mlmodelc")
7
8def run_prediction():
9    # 1. Load the model
10    # ml_model, error = CoreML.MLModel.modelWithContentsOfURL_error_(model_url, None)
11    # Note: Modern versions of CoreML use configuration objects
12    config = CoreML.MLModelConfiguration.alloc().init()
13    ml_model, error = CoreML.MLModel.modelWithContentsOfURL_configuration_error_(
14        model_url, config, None
15    )
16
17    if error:
18        print(f"Error loading model: {error}")
19        return
20
21    # 2. Prepare inputs (matches the features defined in your model)
22    # Using a dictionary-based provider is the quickest way to start
23    input_data = {"input_name": 1.0}
24    provider, error = CoreML.MLDictionaryFeatureProvider.alloc().initWithDictionary_error_(
25        input_data, None
26    )
27
28    if error:
29        print(f"Error creating input provider: {error}")
30        return
31
32    # 3. Perform prediction
33    output, error = ml_model.predictionFromFeatures_error_(provider, None)
34
35    if error:
36        print(f"Error during prediction: {error}")
37        return
38
39    # 4. Access results
40    # Access output features by name as defined in the .mlmodel
41    result = output.featureValueForName_("output_name")
42    print(f"Prediction result: {result}")
43
44if __name__ == "__main__":
45    run_prediction()