python time series predict model multi example code
时间: 2024-06-12 22:05:35 浏览: 104
Here is an example code for a time series prediction model using Python:
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import LSTM, Dense
# Load data
data = pd.read_csv('time_series_data.csv')
# Preprocess data
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
# Split data into training and testing sets
train_size = int(len(data) * 0.8)
train_data, test_data = data.iloc[:train_size], data.iloc[train_size:]
# Define function for creating time series dataset
def create_time_series_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
# Create time series dataset
time_steps = 30
X_train, y_train = create_time_series_dataset(train_data, train_data['Value'], time_steps)
X_test, y_test = create_time_series_dataset(test_data, test_data['Value'], time_steps)
# Build LSTM model
model = Sequential()
model.add(LSTM(units=64, input_shape=(time_steps, 1)))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mse')
# Train model
model.fit(X_train, y_train, epochs=50, batch_size=32)
# Predict on test data
y_pred = model.predict(X_test)
# Evaluate model
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print('RMSE:', rmse)
# Plot predictions vs actual
plt.plot(y_test)
plt.plot(y_pred)
plt.legend(['Actual', 'Predicted'])
plt.show()
```
This code loads in a time series dataset, preprocesses the data, splits it into training and testing sets, creates a time series dataset with a given time step, builds an LSTM model, trains the model, makes predictions on the testing set, evaluates the model using the root mean squared error, and plots the predicted values against the actual values.
阅读全文