The provided code is a utility function for preprocessing time series data to prepare it for training an LSTM (Long Short-Term Memory) model. Here's a detailed breakdown:
1. Key Imports
The imports are standard for time series forecasting with LSTMs:
numpy/pandas: For data manipulation.MinMaxScaler: To normalize data (common for LSTMs, which are sensitive to scale).train_test_split: To split data into training/testing sets.mean_squared_error: To evaluate model performance.TensorFlow Keras: For building the LSTM model.
2. create_dataset Function
This function converts a 1D time series into input-output pairs where:
- Input (
dataX): Sequences oflook_backconsecutive time steps. - Output (
dataY): The next time step immediately after the input sequence.
Parameters
dataset: A 2D numpy array (shape:[n_samples, 1]—since we usedataset[:,0]to extract the feature column).look_back: Number of past time steps to use as input (e.g.,look_back=7means use the last 7 days to predict the 8th).
How It Works
- Loop: For each index
ifrom0tolen(dataset) - look_back -1(to avoid out-of-bounds errors):a = dataset[i:(i+look_back),0]: Slicelook_backconsecutive values from the dataset.dataX.append(a): Add this sequence to input data.dataY.append(dataset[i+look_back,0]): Add the next value (target) to output data.
- Return: Numpy arrays of
dataX(input sequences) anddataY(target values).
Example Usage
Suppose you have a time series of daily sales:
# Sample data (10 days of sales)
sales = np.array([100, 120, 130, 150, 140, 160, 180, 200, 210, 230]).reshape(-1,1)
# Create input-output pairs with look_back=3
X, y = create_dataset(sales, look_back=3)
# Output:
# X = [[100,120,130], [120,130,150], [130,150,140], ...] (each sequence of 3)
# y = [150,140,160, ...] (next value after each sequence)
Next Steps After This Function
To use this data for LSTM:
- Reshape
X: LSTMs expect 3D input (samples, time_steps, features). So:
X = X.reshape(X.shape[0], X.shape[1], 1)(since each sequence haslook_backtime steps and 1 feature). - Split into Train/Test: Use
train_test_split(X, y, test_size=0.2). - Build LSTM Model:
model = Sequential() model.add(LSTM(50, input_shape=(look_back,1))) # 50 LSTM units model.add(Dense(1)) # Output layer (predict 1 value) model.compile(optimizer='adam', loss='mse') - Train:
model.fit(X_train, y_train, epochs=50, batch_size=1) - Evaluate: Compute
mean_squared_error(y_test, model.predict(X_test)).
This function is a core step in time series forecasting with LSTMs, as it transforms raw sequential data into a format the model can learn from. Let me know if you need further clarification!


作者声明:本文包含人工智能生成内容。