首页 > 解决方案 > ML5,情绪分析:未捕获(承诺中)类型错误:无法读取未定义的属性“the”

问题描述

我正在尝试使用ML5 sentimentapi 评估一本书的情绪:

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加载正常,我可以将其打印到控制台。使用该predict方法时会发生以下错误:

在此处输入图像描述

如果我text用一个单词替换,错误保持不变。那么我在这里做错了什么,如何使事情正常进行?

标签: javascriptml5

解决方案


它不起作用,因为在加载模型之前调用了该函数(正如@dwosk所指出的那样)。调用predict必须模型准备好后进行。

换句话说,该函数必须在A处调用,而不是在B处:

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

[B: THIS LOADS BEFORE THE MODEL IS READY]

这是一个工作示例:https ://codepen.io/adelriosantiago/pen/RwaXjez?editors=1011

请注意,fetch为了简单起见,该函数被模拟为返回“a beautiful happy cat”。


推荐阅读