Created
November 8, 2022 06:14
-
-
Save SpiffGreen/3e0d16f9d64fc96c37734b8a5f6237fe to your computer and use it in GitHub Desktop.
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
<html> | |
<head> | |
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script> | |
</head> | |
<body> | |
<script> | |
const urls = { | |
model: | |
"https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json", | |
metadata: | |
"https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json", | |
}; | |
async function loadModel(url) { | |
try { | |
const model = await tf.loadLayersModel(url); | |
return model; | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
async function loadMetadata(url) { | |
try { | |
const metadataJson = await fetch(url); | |
const metadata = await metadataJson.json(); | |
return metadata; | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
const padSequences = (sequences, metadata) => { | |
return sequences.map((seq) => { | |
if (seq.length > metadata.max_len) { | |
seq.splice(0, seq.length - metadata.max_len); | |
} | |
if (seq.length < metadata.max_len) { | |
const pad = []; | |
for (let i = 0; i < metadata.max_len - seq.length; ++i) { | |
pad.push(0); | |
} | |
seq = pad.concat(seq); | |
} | |
return seq; | |
}); | |
}; | |
function predict(text, model, metadata) { | |
const inputText = text | |
.trim() | |
.toLowerCase() | |
.replace(/(\.|\,|!)/g, "") | |
.split(" "); | |
const sequence = inputText.map((word) => { | |
const wordIndex = metadata.word_index[word]; | |
if (typeof wordIndex === "undefined") { | |
return 2; //oov_index | |
} | |
return wordIndex + metadata.index_from; | |
}); | |
const paddedSequence = padSequences([sequence], metadata); | |
const input = tf.tensor2d(paddedSequence, [1, metadata.max_len]); | |
const predictOut = model.predict(input); | |
const score = predictOut.dataSync()[0]; | |
predictOut.dispose(); | |
return score; | |
} | |
// const model = await loadModel(); | |
// const metadata = await getMetaData(); | |
Promise.all([loadModel(urls.model), loadMetadata(urls.metadata)]).then(([model, metadata]) => { | |
const result = predict("you are a good person", model, metadata); | |
console.log("Result: ", result); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment