ML5, sentiment analysis: Uncaught (in promise) TypeError: Cannot read property 'the' of undefined

309 views Asked by At

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:

enter image description here

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?

1

There are 1 answers

0
adelriosantiago On BEST ANSWER

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:

function modelReady() {
  console.log("Model Loaded!");
  [A: THIS LOADS WHEN THE MODEL IS READY]
}

[B: THIS LOADS BEFORE THE MODEL IS READY]

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.