簡體   English   中英

重塑的輸入是具有“batch_size”值的張量,但請求的形狀需要“n_features”的倍數

[英]Input to reshape is a tensor with 'batch_size' values, but the requested shape requires a multiple of 'n_features'

我試圖引起自己的注意 model 我在這里找到了示例代碼: 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}}]]

我認為損失 function 有問題在這里說: 重塑的輸入是具有 2 *“batch_size”值的張量,但請求的形狀具有“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}}]]

細節和以前一樣。 我應該怎么辦?

您的輸入形狀必須是(150,1)

LSTM 形狀是(batch, steps, features) 僅使用 1 步的 LSTM 是沒有意義的。 (除非您使用帶有stateful=True的自定義訓練循環,這不是您的情況)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM