Created
May 8, 2018 20:51
-
-
Save jo-tez/90c633a56c3fbb4768e1604f51a0543d to your computer and use it in GitHub Desktop.
coreml_namesDT.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import objc_util | |
from objc_util import ObjCClass, nsurl, ns | |
''''''''''''''''' | |
CoreML types | |
''''''''''''''''' | |
MLModel = ObjCClass('MLModel') | |
MLDictionaryFeatureProvider = ObjCClass('MLDictionaryFeatureProvider') | |
MLFeatureValue = ObjCClass('MLFeatureValue') | |
def build_features(first_name : str): | |
s = first_name.lower() | |
keys = [] | |
key_dict = {} | |
keys.append('first-letter=' + s[0]) | |
keys.append('first2-letters=' + s[:2]) | |
keys.append('first3-letters=' + s[:3]) | |
keys.append('last-letter=' + s[-1]) | |
keys.append('last2-letters=' + s[-2:]) | |
keys.append('last3-letters=' + s[-3:]) | |
for k in keys: | |
key_dict[k] = 1.00 | |
features = MLDictionaryFeatureProvider.new() | |
features.setDictionary_({ | |
'input' : MLFeatureValue.featureValueWithDictionary_error_(key_dict, None) | |
}) | |
return features | |
if __name__ == '__main__': | |
# Try to load prettained model | |
path = '~/Documents/code/ObjC/NamesDT.mlmodel' | |
path = os.path.expanduser(path) | |
url = nsurl(path) | |
# Only required on first run | |
# Compiled model should be copied to an | |
# accessible directory | |
#compiled_url = MLModel.compileModelAtURL_error_(url, None) | |
compiled_url = nsurl(os.path.expanduser('~/Documents/code/ObjC/NamesDT.mlmodelc/')) | |
model = MLModel.modelWithContentsOfURL_error_(compiled_url, None) | |
person_name = 'Charlie' | |
input = build_features(person_name) | |
pred = model.predictionFromFeatures_error_(input, None) | |
class_label = pred.featureValueForName_('classLabel') | |
class_prob = pred.featureValueForName_('classProbability') | |
print(f'Name: {person_name}') | |
print(f'Predicted: {class_label}') | |
print(f'Probabilities: {class_prob}') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment