【问题标题】:Input to reshape is a tensor with 'batch_size' values, but the requested shape requires a multiple of 'n_features'重塑的输入是具有“batch_size”值的张量,但请求的形状需要“n_features”的倍数
【发布时间】:2019-09-26 19:51:03
【问题描述】:

我正在尝试制作自己的注意力模型,我在这里找到了示例代码: https://www.kaggle.com/takuok/bidirectional-lstm-and-attention-lb-0-043

当我不加修改地运行它时它工作得很好。

但我自己的数据只包含数值,我不得不更改示例代码。

所以我删除了示例代码中的嵌入部分,另外,这是我修复的。

xtr = np.reshape(xtr, (xtr.shape[0], 1, xtr.shape[1])) 
# xtr.shape() = (n_sample_train, 1, 150), y.shape() = (n_sample_train, 6)
xte = np.reshape(xte, (xte.shape[0], 1, xte.shape[1]))
# xtr.shape() = (n_sample_test, 1, 150)

model = BidLstm(maxlen, max_features)
model.compile(loss='binary_crossentropy', optimizer='adam',
              metrics=['accuracy'])

我的 BidLstm 函数看起来像,


def BidLstm(maxlen, max_features):
    inp = Input(shape=(1,150))
    #x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp) -> I don't need embedding since my own data is numeric.
    x = Bidirectional(LSTM(300, return_sequences=True, dropout=0.25,
                           recurrent_dropout=0.25))(inp)
    x = Attention(maxlen)(x)
    x = Dense(256, activation="relu")(x)
    x = Dropout(0.25)(x)
    x = Dense(6, activation="sigmoid")(x)
    model = Model(inputs=inp, outputs=x)

    return model

它说,

InvalidArgumentErrorTraceback (most recent call last)
<ipython-input-62-929955370368> in <module>
     29 
     30     early = EarlyStopping(monitor="val_loss", mode="min", patience=1)
---> 31     model.fit(xtr, y, batch_size=128, epochs=15, validation_split=0.1, callbacks=[early])
     32     #model.fit(xtr, y, batch_size=256, epochs=1, validation_split=0.1)
     33 

/usr/local/lib/python3.5/dist-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1037                                         initial_epoch=initial_epoch,
   1038                                         steps_per_epoch=steps_per_epoch,
-> 1039                                         validation_steps=validation_steps)
   1040 
   1041     def evaluate(self, x=None, y=None,

/usr/local/lib/python3.5/dist-packages/keras/engine/training_arrays.py in fit_loop(model, f, ins, out_labels, batch_size, epochs, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics, initial_epoch, steps_per_epoch, validation_steps)
    197                     ins_batch[i] = ins_batch[i].toarray()
    198 
--> 199                 outs = f(ins_batch)
    200                 outs = to_list(outs)
    201                 for l, o in zip(out_labels, outs):

/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py in __call__(self, inputs)
   2713                 return self._legacy_call(inputs)
   2714 
-> 2715             return self._call(inputs)
   2716         else:
   2717             if py_any(is_tensor(x) for x in inputs):

/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py in _call(self, inputs)
   2673             fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)
   2674         else:
-> 2675             fetched = self._callable_fn(*array_vals)
   2676         return fetched[:len(self.outputs)]
   2677 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in __call__(self, *args, **kwargs)
   1437           ret = tf_session.TF_SessionRunCallable(
   1438               self._session._session, self._handle, args, status,
-> 1439               run_metadata_ptr)
   1440         if run_metadata:
   1441           proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
    526             None, None,
    527             compat.as_text(c_api.TF_Message(self.status.status)),
--> 528             c_api.TF_GetCode(self.status.status))
    529     # Delete the underlying status object from memory otherwise it stays alive
    530     # as there is a reference to status from this from the traceback due to

InvalidArgumentError: Input to reshape is a tensor with 128 values, but the requested shape requires a multiple of 150
     [[{{node attention_16/Reshape_2}}]]
     [[{{node loss_5/mul}}]]

我认为这里的损失函数有问题: Input to reshape is a tensor with 2 * "batch_size" values, but the requested shape has "batch_size"

但我不知道要修复哪个部分。

我的 keras 和 tensorflow 版本是 2.2.4 和 1.13.0-rc0

请帮忙。谢谢。

编辑 1

我已经更改了批量大小,就像 keras 所说的那样,是 150 的倍数(batch_size = 150)。比它报告的要多

Train on 143613 samples, validate on 15958 samples
Epoch 1/15
143400/143613 [============================>.] - ETA: 0s - loss: 0.1505 - acc: 0.9619


InvalidArgumentError: Input to reshape is a tensor with 63 values, but the requested shape requires a multiple of 150
     [[{{node attention_18/Reshape_2}}]]
     [[{{node metrics_6/acc/Mean_1}}]]

细节和以前一样。我该怎么办?

【问题讨论】:

  • 错误数字表明 xtr 形状 (n_sample_train, 1, 150) 与 128 的批量大小不匹配。

标签: python-3.x numpy tensorflow keras


【解决方案1】:

您的输入形状必须是(150,1)

LSTM 形状为(batch, steps, features)。仅使用 1 步的 LSTM 是没有意义的。 (除非您使用带有stateful=True 的自定义训练循环,这不是您的情况)。

【讨论】:

  • 谢谢你的回答,但我对 LSTM 有点困惑,我的数据每行有 150 个特征,而且都是数值,每行有 3 个类标签。我想对每一行做一个预测,那么它的形状应该是 (batch, 1, 150) ?
  • 我已将数据集的形状更改为 (n_sample_train, 150(= n_feature), 1) 并将输入形状更改为 (150(= n_feature), 1)。它终于开始学习了。但我不确定它是否按照我的设计正确学习。我想逐行预测类,每行有 150 个特征。可以将 (n_sample, n_feature) 重塑为 (n_sample, n_feature, 1) 吗?
  • 如果您没有正确解释数据库,则无法判断它是否正确。我不知道行、特征等是什么。LSTM 应该与 (sequences, time_steps, features_per_step) 一起使用。
  • 如果你没有时间步长,或者如果steps是1,也许有一个LSTM没用,另一个模型会表现得更好。
猜你喜欢
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2021-12-31
相关资源
最近更新 更多