基于LSTM与Keras实现未来值预测:调整预测起始至数据末尾
Hey there! Let's work through this together—since you're coming from Java and new to Python/ML, I'll break this down clearly so you understand exactly what's changing and why.
Adjusting Prediction Start to the End of Your Data
The core issue with your current code is that curr_frame = data[-3] is grabbing the third-to-last data point instead of a full valid window from the very end of your dataset. Here's how to fix it and make your prediction start at the latest available data:
Modified Code
def predict_future(model, data, window_size, prediction_len): # Grab the LAST full window of data to start our prediction from curr_frame = data[-window_size:] # Replace data[-3] with this line predicted = [] for i in range(prediction_len): # Reshape the current frame to match what your ML model expects # Most time series models (like LSTMs) need input in shape (batch_size, window_size, num_features) input_data = curr_frame.reshape(1, window_size, -1) # Generate the next prediction (verbose=0 hides unnecessary logging) pred = model.predict(input_data, verbose=0) # Add the prediction to our results list (adjust indices based on your model's output shape) predicted.append(pred[0][0]) # Update the current frame: slide the window forward by dropping the oldest value and adding the new prediction # If data is a numpy array: curr_frame = np.append(curr_frame[1:], pred) # If data is a regular Python list, use this instead: # curr_frame = curr_frame[1:] + [pred[0][0]] return predicted
Key Changes & Explanations
- Starting at the end:
data[-window_size:]uses Python's slicing syntax to grab the lastwindow_sizeelements from your dataset. This ensures we're feeding the model a complete, valid window of recent data to start predicting from—critical because your model was trained on windows of this length. - Shape adjustment: The
reshapestep converts our 1D window into a format most time series models accept. The1is for batch size (we're predicting one batch at a time),window_sizeis the length of our input sequence, and-1automatically adapts to the number of features in your data (e.g., 1 if it's a single-value time series). - Sliding the window: After each prediction, we update
curr_frameby removing the oldest data point and adding our new prediction. This lets us chain predictions together to forecast multiple steps into the future.
Quick Python Tip for Java Devs
Python's slicing (data[-n:], data[1:]) is a shortcut that replaces the manual index calculations you'd do in Java. It's super handy for working with sequences like time series data!
内容的提问来源于stack exchange,提问作者Carson P
相关产品推荐
相关产品推荐

