内容中心

2026年口碑好的宁波智能柜锁精选厂家-宁波望通锁业有限公司

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 of look_back consecutive 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 use dataset[:,0] to extract the feature column).
  • look_back: Number of past time steps to use as input (e.g., look_back=7 means use the last 7 days to predict the 8th).

How It Works

  • Loop: For each index i from 0 to len(dataset) - look_back -1 (to avoid out-of-bounds errors):
    • a = dataset[i:(i+look_back),0]: Slice look_back consecutive 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) and dataY (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:

  1. Reshape X: LSTMs expect 3D input (samples, time_steps, features). So:
    X = X.reshape(X.shape[0], X.shape[1], 1) (since each sequence has look_back time steps and 1 feature).
  2. Split into Train/Test: Use train_test_split(X, y, test_size=0.2).
  3. 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')
  4. Train: model.fit(X_train, y_train, epochs=50, batch_size=1)
  5. 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!

宁波望通锁业有限公司

宁波望通锁业有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?