Here's an example code for LSTM using PyCharm:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
from sklearn.preprocessing import MinMaxScaler

# Load the dataset
df = pd.read_csv('dataset.csv')

# Split the dataset into training and testing sets
train_size = int(len(df) * 0.8)
test_size = len(df) - train_size
train_data = df.iloc[0:train_size, :].values
test_data = df.iloc[train_size:len(df), :].values

# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)

# Prepare the data
def prepare_data(data, look_back=1):
    X, Y = [], []
    for i in range(len(data) - look_back):
        X.append(data[i:(i + look_back), 0])
        Y.append(data[i + look_back, 0])
    return np.array(X), np.array(Y)

look_back = 60
train_X, train_Y = prepare_data(train_data, look_back)
test_X, test_Y = prepare_data(test_data, look_back)

# Reshape the data
train_X = np.reshape(train_X, (train_X.shape[0], train_X.shape[1], 1))
test_X = np.reshape(test_X, (test_X.shape[0], test_X.shape[1], 1))

# Build the LSTM model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(train_X.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
history = model.fit(train_X, train_Y, epochs=100, batch_size=32, validation_data=(test_X, test_Y))

# Predict the prices
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)

# Transform the predicted data back to original scale
train_predict = scaler.inverse_transform(train_predict)
train_Y = scaler.inverse_transform([train_Y])
test_predict = scaler.inverse_transform(test_predict)
test_Y = scaler.inverse_transform([test_Y])

# Calculate the root mean squared error (RMSE)
train_rmse = np.sqrt(np.mean(np.power(train_predict - train_Y, 2)))
test_rmse = np.sqrt(np.mean(np.power(test_predict - test_Y, 2)))

# Plot the results
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('LSTM Model')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()

plt.plot(test_Y[0], label='Actual Price')
plt.plot(test_predict, label='Predicted Price')
plt.title('LSTM Model')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()

print('Train RMSE:', train_rmse)
print('Test RMSE:', test_rmse)

This code demonstrates how to implement an LSTM model in PyCharm for time series prediction. It includes steps for:

  1. Data Preparation: Loading, splitting, and normalizing the data.
  2. Model Building: Defining the LSTM architecture with multiple layers, dropout, and dense output layer.
  3. Model Training: Compiling and fitting the model to the training data.
  4. Prediction: Generating predictions for both training and testing data.
  5. Evaluation: Calculating the root mean squared error (RMSE) to assess model performance.
  6. Visualization: Plotting the training and validation loss, and comparing actual and predicted prices.

This example provides a solid foundation for building and applying LSTM models for diverse time series prediction tasks.

PyCharm LSTM Code Example: Time Series Prediction

原文地址: https://www.cveoy.top/t/topic/m4fe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录