首页 > 解决方案 > 为什么模型历史和模型输出历史总是未定义

问题描述

我是 ML 新手,并尝试使用 TensorFlow.js 来训练我的程序并根据 2 个输入预测输出,但我不确定我是否正确执行此操作,使用代码很容易解释,因此在下面添加它。

下面的代码被调用一次,

const hiddenLayer = tf.layers.dense({
    units: 6,
    inputShape: [2],
    activation: 'sigmoid',
    kernelInitializer: 'leCunNormal',
    useBias: true,
    biasInitializer: 'randomNormal',
});
const outputLayer = tf.layers.dense({ units: 1 });
this.someModel = tf.sequential(); 
this.someModel.add(hiddenLayer);
this.someModel.add(outputLayer);
this.someModel.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });

下面的代码每秒调用一次来训练模型并预测下一个输出,

const  h = this.trainModel();
var inputs = [input1, input2]; 

tf.tidy(() => {
  const outputs = this.someModel.predict(tf.tensor2d([ inputs ]));
  outputs.data().then(output => {
    if (output > 0.5) {
        // do some action     
    }
  });
});

async trainModel() {
console.log("this.someModel.history " + this.someModel.history)
console.log("this.someModel.outputHistory " + this.someModel.outputHistory)

return await this.someModel.fit(tf.tensor2d(this.someModel.history),        tf.tensor1d(this.someModel.outputHistory), {
  shuffle: true,
});
}

this.someModel.history 和 this.someModel.outputHistory 总是在打印以下,

this.someModel.history undefined
this.someModel.outputHistory undefined

而且我收到以下错误,因为它们是未定义的,

Uncaught (in promise) 错误:张量构造函数的输入必须是非空值。

*我究竟做错了什么 ?我不确定为什么我什至需要 model.fit 方法,我猜 predict 函数会在内存中为我的程序建立一个模型,然后根据这个进行预测 *

标签: javascripttypescripttensorflowtensorflow.js

解决方案


您传递给张量构造函数的参数为​​空。这就是您收到错误的原因。

tf.model没有history财产。训练的history由该fit方法返回。因此,如果要获取历史记录,可以这样进行:

history = await this.someModel.fit(tf.zeros([1, 3]) , tf.zeros([1, 1]), {
  shuffle: true,
});
// then you can do whatever you want with the history

但是,通过创建 的一维张量并不清楚您想做什么historyhistory是一个对象,不能用于创建构造函数参数为数组的张量

要训​​练或拟合您的模型,您需要提供您拥有或自己创建的值。这些值不会像您认为的那样由模型本身返回,使用this.someModel.history,this.someModel.outputHistory


推荐阅读