NumPy重塑数组时触发IndexError: tuple index out of range问题求助
Let's walk through why this error is happening and how to fix it for your time series data prep.
What's Causing the Error?
The root issue is in how you're slicing your scaled_data to build x_train:
x_train.append(scaled_data[prediction_days-i:,0])
When i starts at prediction_days (100) and increments, prediction_days - i becomes a non-positive number:
- For
i=100, it's0→ you're taking the entire first column ofscaled_data(length equal to the full dataset) - For
i=101, it's-1→ you're taking only the last 1 element - For
i=102, it's-2→ you're taking the last 2 elements, and so on
This means every entry in x_train has a different length. When you convert this list to a NumPy array with np.array(x_train), you don't get a 2D array like you expect—you get a 1D object array (shape looks like (N,), where N is the number of samples).
Since this array only has one dimension, trying to access x_train.shape[1] (the second dimension) throws the IndexError: tuple index out of range—there is no index 1 in a 1-element shape tuple.
How to Fix It
You're trying to use the previous prediction_days days of data to predict the current day's value, so you need to reverse the slicing logic to get a consistent window of 100 days per sample.
Update your loop code to this:
for i in range(prediction_days, len(scaled_data)): # Grab the 100 days BEFORE the current index i x_train.append(scaled_data[i-prediction_days:i, 0]) y_train.append(scaled_data[i, 0])
After this change:
- Each entry in
x_trainwill be a 100-element array (matching yourprediction_daysvalue) - Converting to
np.array(x_train)will give you a 2D array with shape(len(scaled_data)-100, 100) - The subsequent
reshapecall will work as intended, converting the 2D array into the 3D format required for LSTM models:(number of samples, time steps, features)
Quick Verification Step
Add a print statement after converting to arrays to confirm the shape is correct:
x_train, y_train = np.array(x_train), np.array(y_train) print("x_train shape:", x_train.shape) # Should output (X, 100) where X is your sample count
内容的提问来源于stack exchange,提问作者legar

