Tensorflow.js inputShape与模型输入不匹配

时间:2019-04-18 00:10:28

标签: node.js tensorflow tensorflow.js

这似乎很基本,但我无法弄清楚。

所以我有sample / data / inputs是一个由10个整数组成的数组,而output / label只是一个整数数组。

让我解释一下,因为它可能是我的数据结构不正确。根据10个整数的输入,我告诉模型结果是标签/输出中的1个整数。

最重要的是,我无法批量处理数据,因为它们是连续的。意味着输入向右移动一个,因此sample [i + 1]中的前9个整数是sample [i]的后9个加上一个新的整数。

这是我的编码方式。

let labels = [1,0,0...]

let samples = [[0,1,1,0,1,0,1,1,1,0], ...]

基本上是10个数组的数组。

const model = tf.sequential();
let input = tf.tensor2d(samples);
model.add(tf.layers.dense({ units: 10, batchInputShape: [1, 10], activation: "sigmoid" }));
model.add(tf.layers.dense({ units: 1, activation: "softmax" }));
model.summary();
model.compile({ loss: "meanSquaredError", optimizer: "sgd", metrics: ["accuracy"] });
model.fit(labels, input, { batchSize: 1, shuffle: false, verbose: 1 });

当我尝试使用此输入法或任何其他输入组合时,我得到以下信息

UnhandledPromiseRejectionWarning: Error: Error when checking model input: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see 1 Tensor(s), but instead got the following list of Tensor(s): 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

  

inputShape与模型输入不匹配

该错误表明模型的输入与数据之间存在形状不匹配。

如何解决这个问题?

  • 要素的形状应与batchInputShape相同,或者应比InputShape高一维。 batchInputShape的第一维通常为null,以在训练期间允许使用不同的batchInputShape。但是,通过在此处指定正好为1(与null不同),训练的特征应恰好具有等于1的第一维。如果为零,则可能具有形状[b,.. .InputShape]

  • 标签的形状应为[b, LastLayerUnit]。同样,通过指定批次的硬编码值(与null不同),标签的第一维应完全具有该长度。

什么是批次尺寸?

here是理解它的一个有趣的答案。简单地给出一个模型。下面允许训练模型:

model.fit(features, label)

features是特征数组,而特征是我们要进行预测的元素。因此,批量大小是该数组的长度。知道batchInputShape优先于inputShape,模型的第一层可以具有参数inputShape或batchInputShape或两者都有。当仅提供inputShape时,batchInputShape = [null,... InputShape],因此表明我们可以使用各种长度的要素元素来拟合模型,前提是标签具有相同的标签长度​​,这对于标签有意义为每个功能提供。

因此

      inputShape = batchInputShape[1:] // python notation 
      inputShape = batchInputShape.slice(1) // js notation

无论如何,要素的形状应与inputShape相同。

const model = tf.sequential();
model.add(tf.layers.dense({ units: 10, batchInputShape: [1, 10], activation: "sigmoid" }));
model.add(tf.layers.dense({ units: 1, activation: "softmax" }));
model.summary();
model.compile({ loss: "meanSquaredError", optimizer: "sgd", metrics: ["accuracy"] });


const arr = Array.from({length: 10}, (_, k) => k+1 )
const features =  tf.tensor(arr, [1, 10])
const labels = tf.tensor([1], [1, 1])

logs = await model.fit(features, labels, { batchSize: 1, shuffle: false, verbose: 1 });
console.log(logs)