LSTM (Long Short Term Memory) networks are a special type of RNN (Recurrent Neural Network) that is structured to remember and predict based on long-term dependencies that are trained with time-series data. An LSTM repeating module has four interacting components.
The LSTM is trained (parameters adjusted) with an input window of prior data and minimized difference between the predicted and next measured value. Sequential methods predict just one next value based on the window of prior data. When there is contextual data (before and after) the desired prediction point, a Convolutional Neural Network (CNN) may improve performance with fewer resources to train and deploy the network.
Data Preparation
Data preparation for LSTM networks involves consolidation, cleansing, separating the input window and output, scaling, and data division for training and validation.
Consolidation - consolidation is the process of combining disparate data (Excel spreadsheet, PDF report, database, cloud storage) into a single repository.
Data Cleansing - bad data should be removed and may include outliers, missing entries, failed sensors, or other types of missing or corrupted information.
Inputs and Outputs - data is separated into inputs (prior time-series window) and outputs (predicted next value). The inputs are fed into a series of functions to produce the output prediction. The squared difference between the predicted output and the measured output is a typical loss (objective) function for fitting.
Scaling - scaling all data (inputs and outputs) to a range of 0-1 can improve the training process.
Training and Validation - data is divided into training (e.g. 80%) and validation (e.g. 20%) sets so that the model fit can be evaluated independently of the training. Cross-validation is an approach to divide the training data into multiple sets that are fit separately. The parameter consistency is compared between the multiple models.
Data Generation and Preparation
import numpy as np import matplotlib.pyplotas plt
# Generate data
n =500
t = np.linspace(0,20.0*np.pi,n)
X = np.sin(t)# X is already between -1 and 1, scaling normally needed
Once the data is created, it is converted to a form that can be used by Keras and Tensorflow for training and prediction.
# Set window of past points for LSTM model
window =10
# Split 80/20 into train/test data
last =int(n/5.0)
Xtrain = X[:-last]
Xtest = X[-last-window:]
# Store window number of points as a sequence
xin =[]
next_X =[] for i inrange(window,len(Xtrain)):
xin.append(Xtrain[i-window:i])
next_X.append(Xtrain[i])
# Reshape data to format for LSTM
xin, next_X = np.array(xin), np.array(next_X)
xin = xin.reshape(xin.shape[0], xin.shape[1],1)
The validation test set assesses the ability of the neural network to predict based on new conditions that were not part of the training set. The validation is performed with the last 20% of the data that was separated from the beginning 80% of data.
# Store "window" points as a sequence
xin =[]
next_X1 =[] for i inrange(window,len(Xtest)):
xin.append(Xtest[i-window:i])
next_X1.append(Xtest[i])
# Reshape data to format for LSTM
xin, next_X1 = np.array(xin), np.array(next_X1)
xin = xin.reshape((xin.shape[0], xin.shape[1],1))
# Predict the next value (1 step ahead)
X_pred = m.predict(xin)
# Plot prediction vs actual for test data
plt.figure()
plt.plot(X_pred,':',label='LSTM')
plt.plot(next_X1,'--',label='Actual')
plt.legend()
When performing the validation it is also important to determine how the model performs with without measurements when it uses prior predictions to predict the next outcome. This is important to determine how well the model performs in a predictive application such as model predictive control where the model is projected forward over the control horizon to determine the sequence of optimal manipulated variable moves and possible future constraint violation. Generating predictions without measurement feedback is a forecast.
# Using predicted values to predict next step
X_pred = Xtest.copy() for i inrange(window,len(X_pred)):
xin = X_pred[i-window:i].reshape((1, window,1))
X_pred[i]= m.predict(xin)
# Plot prediction vs actual for test data
plt.figure()
plt.plot(X_pred[window:],':',label='LSTM')
plt.plot(next_X1,'--',label='Actual')
plt.legend()
import numpy as np import matplotlib.pyplotas plt from keras.modelsimport Sequential from keras.layersimport Dense from keras.layersimport LSTM from keras.layersimport Dropout
# Generate data
n =500
t = np.linspace(0,20.0*np.pi,n)
X = np.sin(t)# X is already between -1 and 1, scaling normally needed
# Set window of past points for LSTM model
window =10
# Split 80/20 into train/test data
last =int(n/5.0)
Xtrain = X[:-last]
Xtest = X[-last-window:]
# Store window number of points as a sequence
xin =[]
next_X =[] for i inrange(window,len(Xtrain)):
xin.append(Xtrain[i-window:i])
next_X.append(Xtrain[i])
# Reshape data to format for LSTM
xin, next_X = np.array(xin), np.array(next_X)
xin = xin.reshape(xin.shape[0], xin.shape[1],1)
# Initialize LSTM model
m = Sequential()
m.add(LSTM(units=50, return_sequences=True, input_shape=(xin.shape[1],1)))
m.add(Dropout(0.2))
m.add(LSTM(units=50))
m.add(Dropout(0.2))
m.add(Dense(units=1))
m.compile(optimizer ='adam', loss ='mean_squared_error')
# Fit LSTM model
history = m.fit(xin, next_X, epochs =50, batch_size =50,verbose=0)
# Store "window" points as a sequence
xin =[]
next_X1 =[] for i inrange(window,len(Xtest)):
xin.append(Xtest[i-window:i])
next_X1.append(Xtest[i])
# Reshape data to format for LSTM
xin, next_X1 = np.array(xin), np.array(next_X1)
xin = xin.reshape((xin.shape[0], xin.shape[1],1))
# Predict the next value (1 step ahead)
X_pred = m.predict(xin)
# Plot prediction vs actual for test data
plt.figure()
plt.plot(X_pred,':',label='LSTM')
plt.plot(next_X1,'--',label='Actual')
plt.legend()
# Using predicted values to predict next step
X_pred = Xtest.copy() for i inrange(window,len(X_pred)):
xin = X_pred[i-window:i].reshape((1, window,1))
X_pred[i]= m.predict(xin)
# Plot prediction vs actual for test data
plt.figure()
plt.plot(X_pred[window:],':',label='LSTM')
plt.plot(next_X1,'--',label='Actual')
plt.legend()
plt.show()
# generate new data import numpy as np import matplotlib.pyplotas plt import pandas as pd import tclab importtime
n =840# Number of second time points (14 min)
tm = np.linspace(0,n,n+1)# Time values
lab = tclab.TCLab()
T1 =[lab.T1]
T2 =[lab.T2]
Q1 = np.zeros(n+1)
Q2 = np.zeros(n+1)
Q1[30:]=35.0
Q1[270:]=70.0
Q1[450:]=10.0
Q1[630:]=60.0
Q1[800:]=0.0 for i inrange(n):
lab.Q1(Q1[i])
lab.Q2(Q2[i]) time.sleep(1) print(Q1[i],lab.T1)
T1.append(lab.T1)
T2.append(lab.T2)
lab.close() # Save data file
data = np.vstack((tm,Q1,Q2,T1,T2)).T
np.savetxt('tclab_data.csv',data,delimiter=',',\
header='Time,Q1,Q2,T1,T2',comments='')
Use the measured temperature and heater values to predict the next temperature value with an LSTM model. Validate the model with a new data set in a predictive and forecast mode. The predictive mode predicts one step ahead while the forecast does not use temperature measurements to generate the predictions.
Solution with LSTM Model
The LSTM model is trained with the TCLab 4 hours data set for 10 epochs. The loss function decreases for the first few epochs and then does not significantly change after that.
The model predictions have good agreement with the measurements. The next steps are to perform validation to determine the predictive capability of the model on a different data set.
The validation shows the performance on data that was not used in the training. In this case, a separate data file is generated versus splitting the training and test data.
The forecast is generated by using the prior LSTM predictions to predict future temperatures. The measurements are only used for initializing the predictions and then predictions are used to predict following values.
import pandas as pd import numpy as np import matplotlib.pyplotas plt from sklearn.preprocessingimport MinMaxScaler importtime
# For LSTM model from keras.modelsimport Sequential from keras.layersimport Dense from keras.layersimport LSTM from keras.layersimport Dropout from keras.callbacksimport EarlyStopping from keras.modelsimport load_model
# Load training data file='https://apmonitor.com/do/uploads/Main/tclab_dyn_data3.txt'
train = pd.read_csv(file)
# Scale features
s1 = MinMaxScaler(feature_range=(-1,1))
Xs = s1.fit_transform(train[['T1','Q1']])
# Scale predicted value
s2 = MinMaxScaler(feature_range=(-1,1))
Ys = s2.fit_transform(train[['T1']])
# Each time step uses last 'window' to predict the next change
window =70
X =[]
Y =[] for i inrange(window,len(Xs)):
X.append(Xs[i-window:i,:])
Y.append(Ys[i])
# Reshape data to format accepted by LSTM
X, Y = np.array(X), np.array(Y)
# Allow for early exit
es = EarlyStopping(monitor='loss',mode='min',verbose=1,patience=10)
# Fit (and time) LSTM model
t0 =time.time()
history = model.fit(X, Y, epochs =10, batch_size =250, callbacks=[es], verbose=1)
t1 =time.time() print('Runtime: %.2f s' %(t1-t0))
# Plot loss
plt.figure(figsize=(8,4))
plt.semilogy(history.history['loss'])
plt.xlabel('epoch'); plt.ylabel('loss')
plt.savefig('tclab_loss.png')
model.save('model.h5')
# Verify the fit of the model
Yp = model.predict(X)
# un-scale outputs
Yu = s2.inverse_transform(Yp)
Ym = s2.inverse_transform(Y)
# Using predicted values to predict next step
Xtsq = Xts.copy() for i inrange(window,len(Xtsq)):
Xin = Xtsq[i-window:i].reshape((1, window,2))
Xtsq[i][0]= v.predict(Xin)
Yti[i-window]= Xtsq[i][0]
A second order model is aligned with data by adjusting unknown parameters to minimize the sum of squared errors. The adjusted parameters are K1, τ1, and τ2.
minn∑i=1(TC1,meas,i−TC1,pred,i)2
τ1dTH1dt+(TH1−Ta)=K1Q1
τ2dTC1dt+TC1=TH1
The first 3000 data points train the model and the next 6000 data points validate the model predictions on data that has not been used for training.
Training 2nd-Order Model
Validating 2nd-Order Model
import numpy as np import matplotlib.pyplotas plt from gekko import GEKKO import pandas as pd
file='https://apmonitor.com/do/uploads/Main/tclab_dyn_data3.txt'
data = pd.read_csv(file)
# subset for training
n =3000
tm = data['Time'][0:n].values
Q1s = data['Q1'][0:n].values
T1s = data['T1'][0:n].values
Model Predictive Control (MPC) is applied online with real-time optimizers that coordinate control moves. This case study demonstrates training and replacement of the MPC with an LSTM network. Two prior case studies demonstrate this same approach with an LSTM Network Replacing PID control and SISO (Single Input, Single Output) MPC. In this case study, the LSTM network is trained from a 2x2 MIMO MPC (Single Input Single Output, Model Predictive Control). LSTM (Long Short Term Memory) networks are a special type of RNN (Recurrent Neural Network) that is structured to remember and predict based on long-term dependencies that are trained with time-series data.
Training and testing are often performed once on a dedicated computing platform. The trained model is then packaged for another computing system for predictions as a deployed machine learning solution. The final step of this exercise is to deploy the LSTM controller, independent of the training program. The controller (configuration in lstm_control.pkl and model in lstm_control.h5) can be deployed on embedded architectures without optimizers. Switch to use the TCLab hardware with tclab_hardware = True. Otherwise, the script uses the digital twin simulator.
import tclab importtime import numpy as np import matplotlib.pyplotas plt importpickle from keras.modelsimport load_model
# PID: 1 sec, MPC: 2 sec
cycle_time =2
tclab_hardware =False# switch to True if hardware available
h5_file,s_x,s_y,window =pickle.load(open('lstm_control.pkl','rb'))
model = load_model(h5_file)