Last active
February 29, 2020 12:49
-
-
Save derms/03019a655229d3650632f60850b5fc6d to your computer and use it in GitHub Desktop.
Sample Sentiment model converted into ONNX and run in MarkLogic. Original Model : https://github.com/cocoa-ai/SentimentCoreMLDemo/blob/master/SentimentPolarity/Resources/SentimentPolarity.mlmodel
This file contains hidden or 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 coremltools | |
# Load a Core ML model | |
coreml_model = coremltools.utils.load_spec('SentimentPolarity.mlmodel') | |
# Convert the Core ML model into ONNX | |
onnx_model = onnxmltools.convert_coreml(coreml_model, 'Sentiment Polarity') | |
# Save as protobuf | |
onnxmltools.utils.save_model(onnx_model, 'SentimentPolarity.onnx') |
This file contains hidden or 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
function getWordFrequencies(sentence) { | |
return cts.tokenize(sentence.toLowerCase()).toArray() | |
.filter(token=>token instanceof cts.word) | |
.map(token=>String(token)) | |
.reduce((accum,token)=> { | |
if (!accum[token]) { | |
accum[token] = 1 | |
} else { | |
accum[token] = accum[token] + 1 | |
} | |
return accum | |
},{}) | |
} | |
function wordFrequenciesToOnnxMap(wordFrequencies) { | |
let entries = Object.entries(wordFrequencies) | |
let words = [] | |
let frequencies = [] | |
for (let [word, freq] of entries) { | |
words.push(word) | |
frequencies.push(freq) | |
} | |
return ort.map(ort.string(words,[entries.length]),ort.value(frequencies,[entries.length],"float")) | |
} | |
function classProbabilityToObject(classProbability) { | |
let seq = ort.getValue(classProbability,0) | |
let keys = ort.stringContent(ort.getValue(seq, 0)) | |
let values = ort.valueGetArray(ort.getValue(seq, 1)) | |
let output = {} | |
for (let i=0; i<keys.length;i++) { | |
output[keys[i]] = values[i] | |
} | |
return output | |
} | |
let sentence = "Pizza is awesome"; | |
let wordFreq = getWordFrequencies(sentence) | |
let input = wordFrequenciesToOnnxMap(wordFreq) | |
const session = ort.session(cts.doc("/onnx/model/SentimentPolarity.onnx")); | |
let output = ort.run(session, { input: input }) | |
let result = { | |
"classLabel" : ort.stringContent(output.classLabel), | |
"classProbability" : classProbabilityToObject(output.classProbability) | |
} | |
result | |
/* Sample Output | |
{ | |
"classLabel": [ | |
"Pos" | |
], | |
"classProbability": { | |
"Neg": 0.469456851482391, | |
"Pos": 0.530543148517609 | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment