How to realize the Prediction of LSTM time Series by Python
This article mainly explains "how to achieve LSTM time series prediction by Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to achieve LSTM time series prediction by Python".
Reference data:
There are two columns of data, the date on the left and the number of passengers on the right
Visualize the data:
Import mathimport numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas import read_csv from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error # load dataset dataframe = read_csv ('. / international-airline-passengers.csv',usecols = [1], header = None,engine = 'python',skipfooter = 3) dataset = dataframe.values# changes the integer to floatdataset = dataset.astype (' float32') plt.plot (dataset) plt.show ()
Visualization results:
Let's start with modeling:
Complete code:
Import mathimport numpy import pandas as pd import matplotlib.pyplot as plt from pandas import read_csv from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error def create_dataset (dataset,look_back = 1): dataX,dataY = [], [] for i in range (len (dataset)-look_back-1): a = dataset [I: i+look_back 0] b = dataset [I + look_back,0] dataX.append (a) dataY.append (b) return numpy.array (dataX), numpy.array (dataY) numpy.random.seed (7) dataframe = read_csv ('. / international-airline-passengers.csv',usecols = [1], header = None Engine = 'python') dataset = dataframe.valuesdataset = dataset.astype (' float32') scaler = MinMaxScaler (feature_range = (0prime1)) dataset = scaler.fit_transform (dataset) train_size = int (len (dataset) * 0.67) test_size = len (dataset)-train_sizetrain,test = dataset [0: train_size,:], dataset [train _ size:len (dataset),:] look_back = 1trainXMagazine Y = create_dataset (train,look_back) testX,testY = create_dataset (test Look_back) # reshape input to be [samples, time steps, features] trainX = numpy.reshape (trainX, (trainX.shape [0], look_back,trainX.shape [1])) testX = numpy.reshape (testX, (testX.shape [0], look_back,testX.shape [1])) # create and fit the LSTM network model = Sequential () model.add (LSTM (4m inputbacks shape = (1m lookback)) model.add (Dense (1)) model.compile (loss = 'mean_squared_error') Optimizer = 'adam') model.fit (trainX,trainY,epochs = 100 recordable batchboxes = 1) # make predictionstrainPredict = model.predict (trainX) testPredict = model.predict (testX) # invert predictionstrainPredict = scaler.inverse_transform (trainPredict) trainY = scaler.inverse_transform ([trainY]) testPredict = scaler.inverse_transform (testPredict) testY = scaler.inverse_transform ([testY]) # calculate root mean squared errortrainScore = math.sqrt (mean_squared_error (trainY [0], trainPredict [: 0]) print ('Train Score:% .2f RMSE'% (trainScore)) testScore = math.sqrt (mean_squared_error (testY [0], testPredict [:, 0])) print (' Test Score:% .2f RMSE'% (testScore)) # shift train predictions for plottingtrainPredictPlot = numpy.empty_like (dataset) trainPredictPlot [:,:] = numpy.nanometric Predictive PlotPlotPlotPlotPlotPlotlook _ back:len (trainPredict) + look_back,:] = trainPredict# shift test predictions for plottingtestPredictPlot = numpy.empty_like (dataset) testPredictPlot [: :] = numpy.nantestPredictPlot [len (trainPredict) + (look_back*2) + 1:len (dataset)-1,:] = testPredict# plot baseline and predictionsplt.plot (scaler.inverse_transform (dataset)) plt.plot (trainPredictPlot) plt.plot (testPredictPlot) plt.show ()
Running result:
At this point, I believe you have a deeper understanding of "how to achieve LSTM time series prediction by Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!