Tensorflow.js:检查目标...预期层具有n个尺寸时出错

时间:2019-05-29 11:57:05

标签: javascript tensorflow keras tensorflow.js

我只是从Tensorflow.js开始,正在尝试构建一个简单的模型,将28 x 28的数组作为输入(每个数组代表一张图片)。但是,某些连接并没有完全正确。运行下面的代码片段,我得到:

errors.ts:48 Uncaught (in promise) Error: Error when checking target: expected dense_Dense1 to have 2 dimension(s). but got array with shape 100,28,28
    at new e (errors.ts:48)
    at Od (training.ts:147)
    at e.standardizeUserData (training.ts:1133)
    at training_tensors.ts:427
    at common.ts:14
    at Object.next (common.ts:14)
    at common.ts:14
    at new Promise (<anonymous>)
    at op (common.ts:14)
    at kd (training_tensors.ts:408)

这是代码本身:

// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 100}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]);

model.fit(trainX, trainX, {
  batchSize: 10,
  epochs: 1,
})
<script src='https://cdnjs.cloudflare.com/ajax/libs/tensorflow/1.1.2/tf.min.js'></script>

让我感到困惑的是model.summary()调用返回:

_________________________________________________________________
layer_utils.ts:152 Layer (type)                 Output shape              Param #   
layer_utils.ts:64 =================================================================
layer_utils.ts:152 input1 (InputLayer)          [null,28,28]              0         
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 reshape_Reshape1 (Reshape)   [null,784]                0         
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 dense_Dense1 (Dense)         [null,100]                78500     
layer_utils.ts:74 =================================================================
layer_utils.ts:83 Total params: 78500
layer_utils.ts:84 Trainable params: 78500
layer_utils.ts:85 Non-trainable params: 0
layer_utils.ts:86 _________________________________________________________________

这表明重塑层应将具有形状(批处理784)的数组传递到致密层,但错误表明不是这样。

有人知道我在做什么错吗?任何建议都将受到欢迎!

1 个答案:

答案 0 :(得分:0)

我的输入具有形状(批号28、28),而模型输出具有形状(批号100)。但是,我要求模型在给定输入trainX(分别为trainX的第二个和第一个参数)的情况下预测model.fit

要解决此问题,我只需要将要预测的值的形状更新为(批量,100):

// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 17}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]),
    trainY = tf.ones([100, 17])

model.fit(trainX, trainY, {
  batchSize: 10,
  epochs: 1,
}).then(function() {
  console.log( model.predict(trainX).dataSync() )
})