TensorFlow时间序列模型训练报错:Only one input size may be -1, not both 0 and 1 求助
Hey there! Let's figure out what's causing that annoying Reshape error and get your model training again.
What's Going Wrong?
Looking at your model code, the issue is a tiny syntax mistake in how you defined your Input layer:
inputs = tf.keras.Input(shape=(inputs.shape[1:]))
You wrapped inputs.shape[1:] in an extra pair of parentheses. Since inputs.shape[1:] is already a tuple ((120,14) from your dataset check), adding another set makes the Input layer expect a shape of ((120,14),) — which is a 1D tensor holding a tuple, not the 2D time series tensor you actually have. This throws off the Flatten layer, leading to that "Only one input size may be -1" error when it tries to reshape this invalid input.
The Quick Fix
Just remove those extra parentheses. You have two solid options:
- Hardcode the shape (since you already confirmed it via assertion):
inputs = tf.keras.Input(shape=(120, 14)) - Dynamically grab the shape from the dataset (avoids hardcoding if you tweak parameters later):
Pro tip: Using# Grab one batch to get the input shape (way more efficient than looping the whole dataset) for batch in train_dataset.take(1): sample_inputs, _ = batch # Define Input layer with the correct shape inputs = tf.keras.Input(shape=sample_inputs.shape[1:])take(1)stops after the first batch instead of iterating through everything — saves time!
Why Your Assertion Didn't Catch This
Your assertion checked the shape of inputs coming from the dataset, which was totally correct. The problem popped up later when you incorrectly defined what shape the model expected to receive — the assertion didn't validate the model's input specification, just the dataset's output.
Full Corrected Model Code
Here's the fixed version of your model setup:
# Optional: Grab sample input shape from dataset for batch in train_dataset.take(1): sample_inputs, _ = batch # Build the model with the correct Input layer inputs = tf.keras.Input(shape=sample_inputs.shape[1:]) x = tf.keras.layers.Flatten()(inputs) x = tf.keras.layers.Dense(16, activation="relu")(x) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Compile and train model.compile("adam", loss="mse", metrics=["mae"]) callbacks = [ tf.keras.callbacks.ModelCheckpoint("jena_dense.keras", save_best_only=True) ] history = model.fit(train_dataset, validation_data=valid_dataset, epochs=15, callbacks=callbacks)
Double-Check the Fix
After making the change, verify your model's input shape is correct by running:
print(model.input_shape) # Should output (None, 120, 14)
The None is the batch dimension (which is dynamic, as expected), and the other two dimensions match your dataset's input shape — so the Flatten layer will now work as intended.
内容的提问来源于stack exchange,提问作者ComplexNumber

