[英]How to load a tensorflow.js model in a react web app?
我正在開發一個React Web應用程序(使用Typescript),我想在其中加載tensorflow.js模型,然后在組件更新后每次應用它。 我已經能夠在沒有React的情況下在一個小型演示應用程序中加載並應用我的模型,但是現在遇到了異步加載功能的一些問題:
我的想法是將模型加載到組件的構造函數中,但是異步函數不能在構造函數中使用。 因此,我嘗試制作一種包裝函數:
export default class MyGreatComponent extends React.Component<{pixels}> {
model;
constructor(props) {
super(props);
this.model = this.loadmodel('http://localhost:3333/model.json');
}
async loadmodel(p: any) {
try {
const model = await tf.loadModel(p);
return model;
} catch (error) {
console.log("error while loading model: ");
console.log(error);
return error;
}
}
...
}
然后,當組件更新並且我想應用模型時:
componentDidUpdate() {
... // get data etc
const t4d = tf.tensor4d(imgarray_n, [1, width, height, 3]);
var prediction : any = this.model.predict(t4d);
}
但是,這給出了:
TypeError:this.model.predict不是函數。
因此,我還嘗試了使用promise的包裝函數(如我在此答案中所見):
loadmodel(p: any){
tf.loadModel(p).then(model => {
return model;
});
}
但是諾言似乎永遠無法解決,並且給了我:
TypeError:無法讀取未定義的屬性“預測”
我不確定自己在做錯什么,或者我不理解是什么。 我希望你們能指出這里出了什么問題。 謝謝!
我發現包裝器的想法多么愚蠢,現在不將模型加載到構造函數中,而是將其加載到ComponentDidMount中,從而達到了目的!
async componentDidMount() {
this.model = await tf.loadModel('http://localhost:3333/model.json');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.