【问题标题】:I get ValueError with the ndim when I run model.predict(X)当我运行 model.predict(X) 时,我得到了 ndim 的 ValueError
【发布时间】:2020-04-10 10:49:08
【问题描述】:

我使用此代码在我的数据上训练我的模型

tf.keras.backend.clear_session()
tf.random.set_seed(50)
np.random.seed(50)
train_set = windowed_dataset(x_train, window_size=30, batch_size=15, shuffle_buffer=shuffle_buffer_size)
model = tf.keras.models.Sequential([
  tf.keras.layers.Conv1D(filters=100, kernel_size=5,
                      strides=1, padding="causal",
                      activation="relu",
                      input_shape=[None, 1]),
  tf.keras.layers.LSTM(100, return_sequences=True),
  tf.keras.layers.LSTM(100, return_sequences=True),
  #tf.keras.layers.Dense(30, activation="relu"),
  #tf.keras.layers.Dense(30, activation="relu"),
  tf.keras.layers.Dense(1),
  tf.keras.layers.Lambda(lambda x: x * 400)
])


optimizer = tf.keras.optimizers.Adam(
    learning_rate=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=True,
    name='Adam'
)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(train_set,epochs=100)

这里是model.summary()

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1d (Conv1D)              (None, 30, 100)           600       
_________________________________________________________________
lstm (LSTM)                  (None, 30, 100)           80400     
_________________________________________________________________
lstm_1 (LSTM)                (None, 30, 100)           80400     
_________________________________________________________________
dense (Dense)                (None, 30, 1)             101       
_________________________________________________________________
lambda (Lambda)              (None, 30, 1)             0         
=================================================================
Total params: 161,501
Trainable params: 161,501
Non-trainable params: 0
_________________________________________________________________
None

我正在尝试运行此代码

model.predict(
    x_valid, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
    workers=1, use_multiprocessing=False
)

它会返回此错误消息:

ValueError: 层序的输入 0 与 层:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,1]

我尝试使用此函数 np.array(x_valid).reshape(300,1) 重塑 x_valid,但没有成功。

我已经通过将 ndim 扩展三倍解决了这个问题

    test_input = x_valid[425]
    test_input = np.expand_dims(test_input,axis=0)
    test_input = np.expand_dims(test_input,axis=0)
    test_input = np.expand_dims(test_input,axis=0)

    print(model.predict(test_input))
    # OUTPUT [[[71.46894]]]

【问题讨论】:

    标签: python numpy tensorflow python-3.7 tensorflow2.0


    【解决方案1】:

    问题来自不正确的测试数据维度。 x_input 的形状为 (15,30,1),因此测试数据也必须具有 3-dim 形状(例如 [1,1,1])。在您的代码中,测试数据是一个 1-dim 数组,因此您应该使用 'test_input = np.expand_dims(test_input,axis=0)' 扩展 dims TWICE 以达到 3-dim 数组

    【讨论】:

      【解决方案2】:

      您的问题源于您需要添加 batch_dimension 才能预测一个数据点。

      这在处理 TensorFlow 和 Keras 时是必要的,即使您在单个样本上进行预测,也需要将 batch_size 添加为 1。

      你需要做的是:

      1. 从您的测试集中获取一项(例如,test_input = x_valid[0]
      2. 构造batch_size为1,即test_input = np.expand_dims(test_input,axis=0)
      3. 现在使用模型进行预测,即prediction = model.predict(test_input)

      【讨论】:

      • 我按照上面的说明做了,不幸的是,得到了这个错误“ValueError: Input 0 of layer sequence is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None , 1]"
      猜你喜欢
      • 2019-09-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2021-08-30
      • 2021-04-08
      相关资源
      最近更新 更多