簡體   English   中英

我正在用 python 學習 tensorflow2,我想知道是什么設置了 ndim?

[英]I am learning tensorflow2 in python and i am wondering what sets the ndim?

def build_model(layers):
    model = Sequential()

    # By setting return_sequences to True we are able to stack another LSTM layer
    model.add(LSTM(layers[0], input_shape=(1, 2), return_sequences=True))

    model.add(LSTM(layers[0], input_shape=(1, 2),
        return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Activation("linear"))

    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop", metrics=['accuracy'])
    print("Compile Time : ", time.time() - start)
    return model

然后當我嘗試在構建它后運行 model.fit 時。 那是錯誤被拋出的時候。 這是正在構建的模型和 model.fit 函數的代碼片段。

window = 20
print("X_train", X_train.shape)
print("y_train", y_train.shape)
print("X_test", X_test.shape)
print("y_test", y_test.shape)

model = build_model([1374, window, 100, 1])

model.fit(X_train,
    y_train,
    batch_size=3,
    epochs=5,
    validation_split=0.1,
    verbose=0).

這是錯誤消息。 ValueError:層“順序”的輸入 0 與層不兼容:預期 ndim=3,發現 ndim=2。 什么是 ndim? 它的值對模型有何調整? 我如何理解我設置的 ndim 。

ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 2).

這是打印出來的形狀。

X_train (1032, 2)
y_train (1032, 2)
X_test (344, 2)
y_test (344, 2)

正如@yudhiesh 所建議的,LSTM 需要輸入形狀為[batch, timesteps, feature]形狀 3D 張量,我可以重現您的問題

import tensorflow as tf
inputs = tf.random.normal([32, 8])
lstm = tf.keras.layers.LSTM(4)
output = lstm(inputs)
print(output.shape)

輸出

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-160c5e8d5d9a> in <module>()
      2 inputs = tf.random.normal([32, 8])
      3 lstm = tf.keras.layers.LSTM(4)
----> 4 output = lstm(inputs)
      5 print(output.shape)

2 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
    217                          'expected ndim=' + str(spec.ndim) + ', found ndim=' +
    218                          str(ndim) + '. Full shape received: ' +
--> 219                          str(tuple(shape)))
    220     if spec.max_ndim is not None:
    221       ndim = x.shape.rank

ValueError: Input 0 of layer lstm_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (32, 8)

工作示例代碼

inputs = tf.random.normal([32, 10, 8])
lstm = tf.keras.layers.LSTM(4)
output = lstm(inputs)
print(output.shape)

輸出:

(32, 4)

暫無
暫無

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

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