I am trying to assess sentiment of a book using ML5 sentiment
api:
const sentiment = ml5.sentiment('movieReviews', modelReady)
// When the model is loaded
function modelReady() {
// model is ready
console.log("Model Loaded!");
}
// make the prediction
fetch('../../data/brothers.txt')
.then(response => response.text())
.then(text => {
const prediction = sentiment.predict(text)
console.log(prediction)
createDiv('predicted sentiment - ' + prediction)
})
function setup() {
}
text
is loaded fine, I can print it to the console. The following error happens on the line with the predict
method:
If I substitute text
with a single word, the error stays the same. So what am I doing wrong here, how to make things work?
It doesn't work because the function is called before the model is loaded (as noted by @dwosk as well). Calls to
predict
must be done after the model is ready.In other words, the function must be called at A, not at B:
Here is a working example: https://codepen.io/adelriosantiago/pen/RwaXjez?editors=1011
Please note that the
fetch
function is mocked to return "a beautiful happy cat" for simplicity.