我目前正在创建一个带有react和deeplearn.js的项目,并且在将两者结合起来时遇到了障碍。在我的反应应用程序中,我正在导入this deeplearnjs library模型,我用它来进行分类。不幸的是,当我尝试调用predict()方法时,我收到以下错误:
TypeError: _this.variables is undefined
对于以下部分代码:
SqueezeNet.prototype.predictWithActivation = function (input, activationName) {
var _this = this;
var _a = this.math.scope(function () {
var activation;
var preprocessedInput = _this.math.subtract(input.asType('float32'), _this.preprocessOffset);
当我在普通HTML中使用生成的Javascript时,它可以很好地工作,所以我不确定为什么我在反应中得到这个错误。我觉得它与更严格的React规则或Javascript版本控制有关,但我不确定。
谢谢!
更新
重现这一点的最简单方法如下:
create-react-app
yarn add deeplearn
和yarn add deeplearn-squeezenet
将App.js修改为以下内容:
import React, { Component } from 'react';
import {ENV, Array3D} from 'deeplearn';
import {SqueezeNet} from 'deeplearn-squeezenet';
class App extends Component {
constructor() {
super();
var net = new SqueezeNet(ENV.math);
net.load();
var img = new Image(227, 227);
img.src = 'boat.jpg';
img.onload = function () {
var pixels = Array3D.fromPixels(img)
var res = net.predict(pixels);
};
}
render() {
return (
<div></div>
);
}
}
export default App;
将以下文件下载到公用文件夹:https://raw.githubusercontent.com/PAIR-code/deeplearnjs/master/models/squeezenet/cat.jpg
yarn start
供参考我正在使用react 16.2.0
答案 0 :(得分:0)
您的代码可能会失败,因为某些方法调用是异步的(例如.load()
)。
以下是如何使您的示例使用React:
create-react-app
yarn add deeplearn
和yarn add deeplearn-squeezenet
public folder
修改App.js
,如下所示
import React, { Component } from 'react';
import { ENV, Array3D } from 'deeplearn';
import { SqueezeNet } from 'deeplearn-squeezenet';
const math = ENV.math;
const squeezeNet = new SqueezeNet(math);
class App extends Component {
constructor() {
super();
this.state = {
statusText: 'Loading Squeezenet...'
}
}
buildSuggestions(obj){
return Object.keys(obj).map(
key => `${obj[key].toFixed(5)}: ${key}`
);
}
imageLoadHandler(e) {
const img = e.target;
squeezeNet.load()
.then(() => {
this.setState({ statusText: 'Predicting...' });
const pixels = Array3D.fromPixels(img);
const result = squeezeNet.predict(pixels);
this.setState({ statusText: '' });
squeezeNet.getTopKClasses(result, 5)
.then((obj) => {
this.setState({ statusText: this.buildSuggestions(obj) });
});
});
}
render() {
const text = Array.isArray(this.state.statusText)?
this.state.statusText :
[this.state.statusText];
return (
<div>
<img src="cat.jpg"
alt="cat"
onLoad={this.imageLoadHandler.bind(this)}
/>
<div id="result">
{ text.map(el => <div key={el}>{el}</div>) }
</div>
</div>
);
}
}
export default App;
然后运行yarn start