-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.4.dl_tf_intermediate_timeseries.py
532 lines (422 loc) · 21.6 KB
/
2.4.dl_tf_intermediate_timeseries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#%% LSTM using Keras -Univariate Time Series -> working with train-test mode
#The Long Short-Term Memory network, or LSTM network, is a recurrent neural network that is trained
#using Backpropagation Through Time and overcomes the vanishing gradient problem.
import numpy as np
import pandas as pd
import math, os
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
import gc; gc.enable()
os.chdir("D:\\trainings\\tensorflow")
# fix random seed for reproducibility
seed = 123; np.random.seed(seed); tf.compat.v1.set_random_seed(seed)
#Now, we can load the data set and look at some initial rows and data types of the columns:
data = pd.read_csv('./data/AirPassengers.csv')
#date time conversion
data['TravelDate'] = pd.to_datetime(data['TravelDate'], format='%m/%d/%Y')
data['Passengers'] = data['Passengers'].astype(float)
data.dtypes # Notice the dtype=’datetime[ns]’
#Index: getting time to index
data.set_index('TravelDate', inplace=True)
data.head()
#Convert data into array that can be broken up into training "batches" that we will feed into our
#RNN model.
TS = data['Passengers'] # This format is useful in plotting graph
TS.head(2)
TS.plot()
dataset = np.array(TS)
dataset = dataset.astype('float32')
#LSTMs are sensitive to the scale of the input data, specifically when the sigmoid or
# tanh (default) activation functions are used. It can be a good practice to rescale
#the data to the range of 0 to 1,also called normalizing.
# normalize the dataset
scaler = MinMaxScaler(feature_range=(-1, 1))
dataset = dataset.reshape(-1, 1) # Follwoing function need in this shape else deprecation warning
np.min(np.ravel(dataset)), np.max(np.ravel(dataset))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.85)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print(len(train), len(test))
type(train), type(test)
#Now we can define a function to create a new dataset, as described above.
#The function takes two arguments: the dataset, which is a NumPy array that we want to convert into a
# dataset, and the look_back, which is the number of previous time steps to use as input variables to
# predict the next time period — in this case defaulted to 1.
#This default will create a dataset where X is the number of passengers at a given time (t) and Y is
#the number of passengers at the next time (t + 1).
#It can be configured, and we will by constructing a differently shaped dataset in the next section.
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
#Let’s take a look at the effect of this function on the first rows of the dataset (shown in the
#unnormalized form for clarity).
# reshape into X=t and Y=t+1 using above function
look_back = 5
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
trainX.shape,trainY.shape,testX.shape,testY.shape
trainX[0:look_back], trainY[0:look_back]
#The LSTM network expects the input data (X) to be provided with a specific array structure in the form
#of: [samples, time steps, features].
#Currently, our data is in the form: [samples, features] and we are framing the problem as one time
#step for each sample. We can transform the prepared train and test input data into the expected
#structure using numpy.reshape() as follows:
# reshape input to be [samples, time steps, features]
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))
trainX.shape
#We are now ready to design and fit our LSTM network for this problem.
#The network has a visible layer with 1 input, a hidden layer with 4 LSTM blocks, and
# an output layer that makes a single value prediction. The default 'tanh'
#activation function is used for the LSTM blocks. The network is trained for 100
#epochs and a batch size of 1 is used.
# create and fit the LSTM network
model = tf.keras.models.Sequential()
layers = [1, 50, 100, 1]
model.add(tf.keras.layers.LSTM(layers[1], input_shape=(None, layers[0]), return_sequences=True))
#model.add(Dropout(0.2))
model.add(tf.keras.layers.LSTM(layers[2],return_sequences=False))
#model.add(Dropout(0.2))
model.add(tf.keras.layers.Dense(layers[3], activation=tf.keras.activations.linear))
model.compile(loss="mse", optimizer="adam")
# Train the model
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=1, shuffle=False)
#Once the model is fit, we can estimate the performance of the model on the train and
# test datasets. This will give us a point of comparison for new models.
# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
#Note that we invert the predictions before calculating error scores to ensure that performance is
#reported in the same units as the original data (thousands of passengers per month).
# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
# calculate root mean squared error
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore)) # 1-28, 5-25, 3-33, 10-34, Newshape: 5-26
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore)) # 1-51, 5-60, 3-70, 10-65, Newshape: 5-42
#Finally, we can generate predictions using the model for both the train and test dataset to get a
#visual indication of the skill of the model.
#Because of how the dataset was prepared, we must shift the predictions so that they align on the x-axis
#with the original dataset.
# shift train predictions for plotting
trainPredictPlot = np.empty_like(dataset)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
# shift test predictions for plotting
testPredictPlot = np.empty_like(dataset)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(look_back*2)-1:len(dataset)-1, :] = testPredict
# plot baseline and predictions
plt.plot(scaler.inverse_transform(dataset), color = 'blue', label="Actual")
plt.plot(trainPredictPlot, color = 'red', label="Train_Forecast")
plt.plot(testPredictPlot, color = 'green', label="Test_Forecast")
plt.legend(loc="upper left")
plt.show()
del(data, dataset, train, trainPredict, trainPredictPlot, trainX, trainY, test, testPredict, testPredictPlot, testX, testY); gc.collect()
#%% LSTM using Keras - working with train mode only
#http://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/#comment-409969
import numpy as np
import pandas as pd
import math, os
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
import gc; gc.enable()
os.chdir("D:\\trainings\\tensorflow")
# fix random seed for reproducibility
seed = 123; np.random.seed(seed); tf.compat.v1.set_random_seed(seed)
#Now, we can load the data set and look at some initial rows and data types of the columns:
data = pd.read_csv('./data/AirPassengers.csv')
#date time conversion
data['TravelDate'] = pd.to_datetime(data['TravelDate'], format='%m/%d/%Y')
data['Passengers'] = data['Passengers'].astype(float)
data.dtypes # Notice the dtype=’datetime[ns]’
#Index: getting time to index
data.set_index('TravelDate', inplace=True)
data.head()
# Just to view
TS = data['Passengers']
TS.head(2)
TS.plot()
#Convert data into array that can be broken up into training "batches" that we will
#feed into our RNN model.
dataset_org = np.array(TS).astype('float32')
# Follwoing function will shift one element right and return difference only
#data_org = np.array([4, 3, 2])
def get_diff(data_org):
data_org = np.array(data_org)
data_diff = data_org[1:] - data_org[:-1]
return(data_diff)
# get_diff
#data_diff = get_diff(data_org)
#data_org.size, data_diff.size
# It inverse the diff
#last_data_point_of_org = data_org[-1]; diff_pred = np.array([3, 1])
def inverse_diff(last_data_point_of_org, diff_pred):
pred = np.append(np.ravel(last_data_point_of_org), np.ravel(np.array(diff_pred)))
pred = np.cumsum(pred)
pred = pred[1:]
return(pred)
# inverse_diff(last_data_point_of_org, diff_pred)
# To make stationary, let us take diff. It will shorten the length by one(first element
# will be removed)
dataset = get_diff(dataset_org)
dataset_org.size, dataset.size
# normalize the dataset
scaler = MinMaxScaler(feature_range=(-1, 1)) # The default activation function for LSTMs is the hyperbolic tangent (tanh), which outputs values between -1 and 1.
dataset = dataset.reshape(-1, 1) # Follwoing function need in this shape else deprecation warning
dataset = scaler.fit_transform(dataset)
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1, b_train_only = False):
if b_train_only:
dataX = []
for i in range(len(dataset)-look_back+1): # i = 138
a = dataset[i:(i+look_back), 0]
dataX.append(a)
return(np.array(dataX))
else:
dataX, dataY = [], []
for i in range(len(dataset)-look_back): # i = 138
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return(np.array(dataX), np.array(dataY))
# reshape into X=t and Y=t+1 using above function
look_back = 5
trainX, trainY = create_dataset(dataset, look_back)
trainX.shape, trainY.shape
#scaler.inverse_transform(trainX[0]), scaler.inverse_transform(trainY[0:1])
#scaler.inverse_transform(trainX[trainX.shape[0]-1]), scaler.inverse_transform(trainY[(trainY.shape[0]-1):trainY.shape[0]])
# reshape input to be [samples, time steps, features]
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
trainX.shape
# create and fit the LSTM network
model = tf.keras.models.Sequential()
layers = [1, 100, 100, 100, 1] # [1, 50, 75, 100, 1]
model.add(tf.keras.layers.LSTM(layers[1], input_shape=(None, layers[0]), return_sequences=True)) # note that you only need to specify the input size on the first layer.
#model.add(Dropout(0.2))
model.add(tf.keras.layers.LSTM(layers[2],return_sequences=True)) # to stack recurrent layers, you must use return_sequences=True on any recurrent layer that feeds into another recurrent layer.
model.add(tf.keras.layers.LSTM(layers[3],return_sequences=False))
#model.add(Dropout(0.2))
model.add(tf.keras.layers.Dense(layers[4], activation=tf.keras.activations.linear))
model.compile(loss="mae", optimizer="adam") # rmsprop adam
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=1, shuffle=False)
# Predict for next 12 steps.
pred_time_steps = 12; pred = np.array([]) # np.array(range(pred_time_steps), dtype = np.float64)
for time_step in range(pred_time_steps): # time_step = 0
# Store previous prediction
#trainX_full = np.append(dataset, trainPredict[len(trainPredict)-1-time_step:len(trainPredict)])
#Default
trainX_full = dataset # Default. Last6: [1.], [ 0.96911204], [ 0.77992272], [ 0.6891892 ], [ 0.55212355], [ 0.63320458]
if len(pred) == 0:
trainX_full = dataset[-look_back:]
else:
trainX_full = np.append(dataset, pred)
trainX_full = trainX_full[-look_back:]
trainX_full = trainX_full.reshape(-1, 1) # Follwoing function need in this shape else deprecation warning
# Create new train set including the last one
trainX_full = create_dataset(trainX_full, look_back, b_train_only= True)
# reshape input to be [samples, time steps, features]
trainX_full = np.reshape(trainX_full, (trainX_full.shape[0], trainX_full.shape[1], 1))
# make predictions
trainPredict = model.predict(trainX_full)
# Get the last value. Note: The first prediction is already in main dataset and
#hence not adding at top of for loop
pred = np.append(pred, trainPredict[len(trainPredict)-1])
del(trainX_full)
# for time_step in range(pred_time_steps):
# Inverse scalling
# It has both original and pred too
trainPredictPlot = np.append(dataset, pred)
trainPredictPlot = trainPredictPlot.reshape(-1, 1) # Follwoing function need in this shape else deprecation warning
trainPredictPlot = scaler.inverse_transform(trainPredictPlot)
# Bring back in pure numpy from share (-1,1) to (-1)
trainPredictPlot = np.array(np.ravel(trainPredictPlot))
trainPredictPlot[0:len(dataset)] = np.nan
trainPredictPlot[-pred_time_steps:] = inverse_diff(dataset_org[-1], trainPredictPlot[-pred_time_steps:])
# Check only
len(dataset_org), len(dataset), len(trainPredictPlot)
# plot baseline and predictions
plt.plot(dataset_org, color = 'blue', label="Actual")
plt.plot(trainPredictPlot, color = 'green', label="Forecast")
plt.legend(loc="upper left")
plt.show()
#CW: Do the self predict on train and clculate RMSE
#CW: How to increase accuracy - Epoch, Batch size, LSTM Layer, Neuron Gates, Dropout,
#%% Multivariate Time Series using LSTM
#https://archive.ics.uci.edu/ml/machine-learning-databases/00381/
import numpy as np
import pandas as pd
import math, os
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
import gc; gc.enable()
os.chdir("D:\\trainings\\tensorflow")
# fix random seed for reproducibility
seed = 123; np.random.seed(seed); tf.compat.v1.set_random_seed(seed)
#Now, we can load the data set and look at some initial rows and data types of the columns:
data = pd.read_csv('./data/PRSA_data_2010.1.1-2014.12.31.csv')
#Remove special char '.' from column name
data.columns = data.columns.str.replace('.', '')
#Few constants for easy reading
col_date = 'date'
col_label = 'pm25'
#date time conversion. Converting for each day only just to keep data short and simple
data[col_date] = pd.to_datetime(data[['year', 'month', 'day']], format='%Y %m %d')
#Drop unwanted columns
data.drop(['No','year', 'month', 'day', 'hour','cbwd'], axis=1, inplace=True)
#See first 24 rows missing response value
#data.dropna(inplace=True)
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
#Aggregate or each day only just to keep data short and simple
data = data.groupby([col_date], as_index=False).mean()
col_features = np.setdiff1d(data.columns,np.array([col_date, col_label]))
data[np.append(np.array([col_label]), np.array(col_features))] = data[np.append(np.array([col_label]), np.array(col_features))].apply(lambda x: x.astype(np.float64))
data.dtypes # Notice the dtype=’datetime[ns]’
#First view
plt.plot(data[col_date], data[col_label])
# normalize the dataset
scaler = MinMaxScaler(feature_range=(-1, 1)) # The default activation function for LSTMs is the hyperbolic tangent (tanh), which outputs values between -1 and 1.
data[col_features] = scaler.fit_transform(data[col_features])
data.head(2)
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX =[]
dataY =[]
for row_num in range(len(dataset)-look_back):
one_dataset=[]
for j in range(0,look_back):
one_dataset.append(dataset[[(row_num+j)], 2:])
dataX.append(one_dataset)
dataY.append(dataset[row_num + look_back-1,1])
return np.array(dataX, dtype = np.float64), np.array(dataY, dtype = np.float64)
#end
# reshape into X=t and Y=t+1 using above function
look_back = 5
trainX, trainY = create_dataset(data.values, look_back)
# reshape input to be [samples, time steps, features]
trainX = trainX.reshape(trainX.shape[0], look_back, len(col_features))
trainX.shape,trainY.shape
#Now let us see how these have been prepared
data.head(6)
trainX[0]
trainY[0]
data.tail(5)
trainX[-1]
trainY[-1]
# create and fit the LSTM network
model = tf.keras.models.Sequential()
layers = [1, 100, 100, 100, 1] # [1, 50, 75, 100, 1]
model.add(tf.keras.layers.LSTM(layers[1], input_shape=(trainX.shape[1],trainX.shape[2]), return_sequences=True)) # note that you only need to specify the input size on the first layer.
model.add(tf.keras.layers.LSTM(layers[2],return_sequences=True)) # to stack recurrent layers, you must use return_sequences=True on any recurrent layer that feeds into another recurrent layer.
model.add(tf.keras.layers.LSTM(layers[3],return_sequences=False))
model.add(tf.keras.layers.Dense(layers[4], activation=tf.keras.activations.linear))
model.summary()
model.compile(optimizer="adam", loss="mae")
model.fit(trainX, trainY, epochs=1000, batch_size=32, verbose=1, shuffle=False)
pred= np.ravel(model.predict(trainX))
np.max(trainY), np.min(trainY)
np.max(pred), np.min(pred)
# plot baseline and predictions
plt.plot(trainY, color = 'blue', label="Actual")
plt.plot(pred, color = 'green', label="Forecast")
plt.legend(loc="upper left")
plt.show()
del(data, col_date, col_label, col_features, scaler, look_back, trainX, trainY, model, layers, pred)
#%% CW: Practice GRU
#%% CW: Practice Bidirectional LSTM
#%% ppt: How to know models are good enough: Bias vs Variance
#%%Language Modelling: Predict next word
# Language models can be operated at character level, n-gram level, sentence level or even paragraph level.
import numpy as np
import pandas as pd
import math, os
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
#import keras.utils as ku
import gc; gc.enable()
os.chdir("D:\\trainings\\tensorflow")
# fix random seed for reproducibility
seed = 123; np.random.seed(seed); tf.compat.v1.set_random_seed(seed)
tokenizer = Tokenizer() #Keep in global as required for test data too
#It prepares data. 1. n(2) gram as predictor 2. Corrosponding out word as label 3. pre padding
def dataset_preparation(data):
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words_count = len(tokenizer.word_index) + 1
input_sequences = []
for line in corpus: # line = corpus[1]
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
trainX, trainY = input_sequences[:,:-1],input_sequences[:,-1]
trainY = tf.keras.utils.to_categorical(trainY, num_classes=total_words_count)
return trainX, trainY, max_sequence_len, total_words_count
#end of dataset_preparation
def create_model(trainX, trainY, max_sequence_len, total_words_count):
input_len = max_sequence_len - 1
model = Sequential()
model.add(Embedding(total_words_count, 10, input_length=input_len)) # Length of input sequences, when it is constant. This argument is required if you are going to connect Flatten then Dense layers upstream (without it, the shape of the dense outputs cannot be computed).
model.add(LSTM(150, return_sequences=False)) # If more layer need to be added then return_sequences=True
model.add(Dropout(0.1))
model.add(Dense(total_words_count, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(trainX, trainY, epochs=500, verbose=1)
return model
#end
#Transform test text similar to train text so that prediction starts.
#test_text = "cat and"; next_words_len = 3;
def prepare_test_text_and_predict(test_text, next_words_len, max_sequence_len, model):
for j in range(next_words_len): # j = 0
token_list = tokenizer.texts_to_sequences([test_text])[0]
token_list = pad_sequences([token_list], maxlen= max_sequence_len-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
test_text += " " + output_word
return test_text
#end
#####Start processing
#Read data
data = pd.read_csv('./data/twinkle_text.csv')
data = str(data.values)
#Advice: Make sure text is cleaned in actual projects
#Prepare data
trainX, trainY, max_sequence_len, total_words_count = dataset_preparation(data)
#Build model and train
model = create_model(trainX, trainY, max_sequence_len, total_words_count)
#Prepare Test and Predict
text = prepare_test_text_and_predict("twinkle twinkle", 2, max_sequence_len, model)
text # "twinkle twinkle little star'"
text = prepare_test_text_and_predict("know not", 2, max_sequence_len, model)
text # 'know not twinkle not'
text = prepare_test_text_and_predict("cat and dog", 2, max_sequence_len, model)
text # 'cat and dog i i'