-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTENSORFLOW RNN.py
More file actions
1853 lines (788 loc) · 26.2 KB
/
TENSORFLOW RNN.py
File metadata and controls
1853 lines (788 loc) · 26.2 KB
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# ## TENSORFLOW 02 . BUILDING A RNN 21 APR 2021
# #### Install required libraries for data manipulation
# In[1]:
import numpy as np
import pandas as pd
import math
# In[2]:
import matplotlib.pyplot as plt
# #### Install required libraries for Tensor flow and Neural Network creation
# In[3]:
##### 1.1 Install tensorflow
# In[4]:
import tensorflow as tf
# In[5]:
print(tf.version.VERSION)
# ##### 1.2 Install keras
# In[6]:
from tensorflow import keras
# ##### 1.3 Install neural network types and configurations
# In[7]:
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# In[8]:
## Get my working directory
import os
path = os.getcwd()
# In[9]:
os.chdir('C:/Pablo UK/46 DATA SCIENCE all/44 Python')
# In[10]:
# Sales_clean.to_csv (r'Sales_clean_plot_csv.csv', index = False, header=True)
# In[11]:
Sales_clean = pd.read_csv('Sales_clean_plot_csv.csv')
# In[12]:
pivot = Sales_clean.copy()
# In[13]:
pivot.head()
# In[14]:
list(pivot.columns.values)
# In[15]:
SalesP = pd.pivot_table(Sales_clean,
values = 'Sales',
index=['PERIOD'],
columns = 'Orgname').reset_index()
# In[16]:
SalesP['PERIOD'] = pd.to_datetime(SalesP['PERIOD'])
# In[17]:
SalesP.set_index("PERIOD",inplace=True)
# In[18]:
SalesP.plot()
# In[19]:
SalesQ = pivot.copy()
# In[20]:
SalesQ.head()
# In[21]:
list(SalesQ.columns.values)
# In[22]:
SalesQ.reset_index()
# In[23]:
list(SalesQ.columns.values)
# #### Subset columns
# In[24]:
SalesR = SalesQ[["PERIOD","Orgname","Sales"]]
# In[25]:
SalesR.head()
# In[26]:
list(SalesQ.columns.values)
# In[27]:
type(SalesQ)
# In[28]:
dataTypeSeries = SalesQ.dtypes
# In[29]:
print('Data type of each column of Dataframe :')
print(dataTypeSeries)
# In[30]:
print (type((SalesQ)))
# #### Subset variable names, select just East Coast branch
# We subset varibale values by using the double equal sign, first we quaote the dataset and then the variable within the dataset, and then we assign the value we want to filter for, in this case 'East coast branch', using single quotes
# **Saleseast = SalesQ[SalesQ['Orgname'] =='East coast branch']**
# This code abote is how you subset rows based on a variable value
# In[31]:
Saleseast = SalesQ[SalesQ['Orgname'] =='East coast branch']
# In[32]:
Saleseast.head()
# In[33]:
Saleseast
# Check again total number of colums in dataframe
# In[34]:
list(SalesQ.columns.values)
# ### Treat PERIOD as date
# In[35]:
Saleseast['PERIOD'] = pd.to_datetime(Saleseast['PERIOD'])
# In[36]:
Saleseast.set_index("PERIOD",inplace=True)
# In[37]:
Saleseast.head()
# ### Subset again columns
# In[38]:
Saleseastmod = Saleseast[["Orgname","Sales"]]
# In[39]:
Saleseastmod.head()
# In[40]:
list(Saleseastmod.columns.values)
# In[41]:
Saleseastmod.reset_index()
# ### Rename column names
# We can rename second col and get rid of Orgname
# In[42]:
Sales_new = Saleseastmod.rename(columns ={'Sales':'Sales_east'})
# In[43]:
Sales_new
# ### 1 Remove null values
# In[44]:
Sales_new.isnull().sum()
# Not required this time as there are not any null values
# Check this notebook on how to remove null values from at TS dataframe "TENSORFLOW Data prep and removing null values"
# #### This is the script to remove null values replacing them by same day previous week value
# for row in range(0,len(SalesQ)):
# SalesQ['Eastbranch']=np.where(
# (np.isnan(SalesQ['Eastbranch'])),
# SalesQ['Eastbranch'].shift(7),SalesQ['Eastbranch']
# )
# In[45]:
SalesQ.isnull().sum()
# for row in range(0,len(SalesQ)):
# SalesQ['Westbranch']=np.where(
# (np.isnan(SalesQ['Westbranch'])),
# SalesQ['Westbranch'].shift(7),SalesQ['Westbranch']
# )
# In[46]:
SalesQ.isnull().sum()
# In[47]:
SalesQ.head()
# ### 2 Subset again data
# In[48]:
Sales_new.head()
# In[49]:
Mydata = Sales_new[["Sales_east"]]
# In[50]:
Mydata.head()
# ### 3 Plot East Sales
# Replace any value above 1000 by standard 150 value/ Average
# In[51]:
Mydata.plot()
# Enhance this plot
# Using matplotlib import matplotlib.pyplot as plt
# In[52]:
Mydata.plot(figsize=(8,5))
plt.grid(True)
## Change scale
plt.title("East coast Sales. 2016.05-2019.05")
plt.gca().set_ylim(0,2000) # This sets vertical range to [0-1]
plt.show()
# We can setup a dark background from matplotlib
# In[53]:
plt.style.use('dark_background')
# In[54]:
Mydata.plot(figsize=(10,7))
plt.grid(True)
## Change scale
plt.title("East coast Sales. 2016.05-2019.05",fontname ="Times New Roman",fontweight ="bold")
plt.gca().set_ylim(0,2000)
plt.ylabel('sales')
plt.xlabel('date')
plt.show()
# ### 4 Remove outliers
# We need to remove extreme values
# In[55]:
Mydata.head()
# In[56]:
type(Mydata)
# #### 4.1 Identify max and max values
# We use a combination of dataset, variable name and max function to obtain the max value
# In[57]:
max_sales = Mydata["Sales_east"].max()
# In[58]:
max_sales
# We use a combination of dataset, variable name and min function to obtain the min value
# In[59]:
min_sales = Mydata["Sales_east"].min()
# In[60]:
min_sales
# #### 4.3 Replace outliers by average value
# We can use the same logic as in the max calculation to get the mean sales value
# In[61]:
avg_sales = Mydata["Sales_east"].mean()
# In[62]:
avg_sales
# So then we only have to replace that extreme value by the mean. by using the replace function
# In[63]:
Mydatab = Mydata.copy()
# In[64]:
len(Mydata)
# This is the standard replace function from Pandas
# df.replace(current_value,new_value)
# In[65]:
max
# In[66]:
Mydatab["Sales_east"].max()
# In[67]:
Mydatab["Sales_east"].mean()
# In[68]:
max_Mydatab = Mydatab["Sales_east"].max()
# In[69]:
max_Mydatab
# We could have replaced outliers by a specific value
# SalesQ.loc[SalesQ.Eastbranch >1000,"Eastbranch"] = 300
# SalesQ.loc[SalesQ.Eastbranch >1000,"Eastbranch"] = 300
# We use this approach
# In[70]:
Mydatab.loc[Mydatab.Sales_east >1000,"Sales_east"] = 174
# SalesQ.loc[SalesQ.Westbranch >1000,"Westbranch"] = 300
# **This is a way of replacing values above a certain treshold by the mean value**
# In[72]:
Mydatab.loc[Mydatab.Sales_east >1000,"Sales_east"] = Mydata["Sales_east"].mean()
# #### 4.4 Plot new dataset
# Plot resulting series
# We change plot color in the plot statement.(darkorange,coral,gold,dodgerblue)
# In[73]:
Mydatab.plot(figsize=(8,5),color ="gold")
plt.grid(True)
## Change scale
plt.title("East coast Sales excluding outliers. 2016.05-2019.05")
plt.gca().set_ylim(0,300) # This sets vertical range to [0-1]
plt.show()
# In[74]:
Mydatab.plot(figsize=(8,5),color ="dodgerblue")
plt.grid(True)
## Change scale
plt.title("East coast Sales excluding outliers. 2016.05-2019.05")
plt.gca().set_ylim(0,300) # This sets vertical range to [0-1]
plt.show()
# In[75]:
Mydatab.plot(figsize=(8,5),color ="mediumspringgreen")
plt.grid(True)
## Change scale
plt.title("East coast Sales excluding outliers. 2016.05-2019.05")
plt.gca().set_ylim(0,300) # This sets vertical range to [0-1]
plt.show()
# In[76]:
Mydatab.plot(figsize=(8,5),color ="orangered")
plt.grid(True)
## Change scale
plt.title("East coast Sales excluding outliers. 2016.05-2019.05")
plt.gca().set_ylim(0,300) # This sets vertical range to [0-1]
plt.show()
# We can also remove the very low values
# In[77]:
Mydatab.loc[Mydatab.Sales_east <100,"Sales_east"] = 174
# In[78]:
Mydatab.plot(figsize=(10,9),color ="mediumpurple")
plt.grid(True)
## Change scale
plt.title("East coast Sales excluding outliers. 2016.05-2019.05",fontweight="bold")
plt.gca().set_ylim(0,300) # This sets vertical range to [0-1]
plt.show()
# Now the serie is ready to carry on with it
# In[79]:
Mydatab.head()
# ## 5 Start modelling using Neural networks
# Check CUDA installation. New CUDA drivers not installed in this Anaconda version
# In[80]:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
# ### 5.1 Split original data into train validation and hold sets
# #### 1. Split main dataset into Train Validation and Hold subsets of data
# #### Train (70%, 84), Validation (20%, 24), Hold (10%, 12). Total rows 120
# * Train (70%, 84),
# * Validation (20%, 24),
# * Hold (10%, 12). Total rows 120
# In[81]:
len(Mydatab)
# In[82]:
Mydatab
# **Tip**: Always check the start and end date of the original dataset before splitting it into Train validation and hols datasets
# When we display the entire dataset, we know that the start date is 2016-05-30 abd the end date is 2019-05-02
# ####Training dataset (70%, 84)
# traindata = Emergency_admissions.iloc[0:84]
# * Train
# In[84]:
906*70/100
# * Validation
# In[85]:
906*20/100
# * Hold
# In[86]:
906*10/100
# In[87]:
# Training dataset (70%, 634 of 906)
traindata = Mydatab.iloc[0:634]
# In[88]:
len(traindata)
# In[89]:
traindata.head()
# In[90]:
traindata
# In[91]:
634+181
# In[92]:
# Validation dataset (20%, 181 of 906)
valdata = Mydatab.iloc[634:815]
# In[93]:
valdata
# In[94]:
# Hold dataset (10%, 90 of 906)
hold = Mydatab.iloc[815:]
# In[95]:
hold
# So finally this is the perfect way as we split succcessfully the original dataset into *Train* *Test* and *Hold* datasets
# ## Training dataset (70%, 634 of 906)
# traindata = Mydatab.iloc[0:634]
# ## Validation dataset (20%, 181 of 906)
# valdata = Mydatab.iloc[634:815]
# ## Hold dataset (10%, 90 of 906)
# hold = Mydatab.iloc[815:]
# This is the dataset split
# - **Training dataset (70%, 634 of 906)**
# * traindata = Mydatab.iloc[0:634]
# - **Validation dataset (20%, 181 of 906)**
# * valdata = Mydatab.iloc[634:815]
# - **Hold dataset (10%, 90 of 906)**
# * hold = Mydatab.iloc[815:]
# In[96]:
# Training dataset (70%, 634 of 906)
traindata = Mydatab.iloc[0:634]
# In[97]:
traindata = Mydatab.iloc[0:634]
# In[98]:
plt.figure(figsize=(15,7))
plt.title('Sales. Split into train Validation and Hold datasets',fontweight="bold")
plt.plot(traindata, label = "Training dataset") # Dataset
plt.plot(valdata, label = "Validation datasett") # Dataset
plt.plot(hold, label = "Hold dataset") # Dataset
plt.legend()
plt.ylabel("value")
plt.xlabel("days")
plt.show()
# In[99]:
type(traindata)
# In[100]:
traindata_test = traindata.copy()
# In[101]:
type(traindata_test)
#
# ### 6.1 Setup Scaler
# This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between **zero** and **one**.Transform features by scaling each feature to a given range.
# We will use the The Min Max Scaler library from skelarn
# In[102]:
from sklearn.preprocessing import MinMaxScaler
# In[103]:
# The dataset will be scaled between 0 and 1
# Initialize the scaler
scaler = MinMaxScaler(feature_range=(0,1))
# In[104]:
scaler
# ### 6.2 Scale **TRAIN** dataset
# ### 6.2.1. Train dataset scaled using MinMaxScaler. The data will be scaled between 0 and 1
# ### 6.2.2 We apply the MinMaxScaler to the Train dataset. It applies to 2d objects
# The MinMaxScaler function must be aaplied on a DataFrame. It expects a 2d object. So we need to heck for the traindata dataframe whether it is a 2d object by using the .shape() function
# #### Training dataset (70%, 634 of 906)
# #### traindata = Mydatab.iloc[0:634]
# Check first Traindata shape
# In[105]:
traindata.shape
# In[106]:
print("Length of the original Traindata is:",len(traindata))
# In[ ]:
# In[107]:
Traindata = scaler.fit_transform(traindata)
# ### 6.2.3 Scaled dataset turn into an series 1D object for the Network setup
# In[108]:
flat_Traindata = Traindata.flatten()
# In[109]:
flat_Traindata.shape
# In[110]:
type(flat_Traindata)
# Remember we need to setup the series accordingly to the traindata index, as this is our original traindata data set
# In[111]:
Traindata_scaled = pd.Series(flat_Traindata,
index=traindata.index)
# ### 6.2.4 Build Target and Features dataset from Traindata_scaled dataset
# In[112]:
Traindata_scaled
# Remember that we just transformed the scaled dataset into a Series object
# In[113]:
type(Traindata_scaled)
# In[114]:
print("Length of the Series object is:",len(Traindata_scaled))
# Define number of lags (5)
# In[115]:
total_lags = 5
# ### 6.2.5 TARGET TRAIN dataset defined as Y_train
# We start by defining the Target dataset from the Traindata scaled dataset
# In[116]:
Y_train = Traindata_scaled.iloc[5:,]
# In[117]:
Y_train
# In[118]:
type(Y_train)
# In[119]:
print("Train dataset defined as Y_train length:",len(Y_train))
# This is the result of gettinf from the 5th row onwards data for Train dataset
# ### 6.2.6 FEATURES TRAIN dataset defined as X_train is a reversed dataframe
# For this step we use the function we build on the P200 Adhoc Functions script
# In[120]:
total_lags = 5
# Remember we defined total_lags as 5 for the above function
# Also the data input to our get_features function, is the traindata we have scaled betwen 0 and 1 earlier
# In[121]:
# Traindata_scaled = pd.Series(flat_Traindata,
# index=traindata.index)
# For recurrent neural networks, the features dataframe (X_train) from the Train dataset, must be build in reversed order starting with t-5 and then going all the way down to t-1 t-4,t-3,t-2,t-1 columns.
# ### For a recurrent neural network the order of theTrain Features X_tran dataframe must be t-5,t-4,t-3,t-2,t-1
# Then we apply the get_features() function
# In[122]:
def get_features(data,total_lags):
columns = []
for each_lag in range(total_lags,0, -1):
Lag_i = pd.DataFrame(data.shift(each_lag +1,axis=0,fill_value=0))
columns.append(Lag_i)
features =pd.concat(columns,axis=1)
# Include column labels
labfeatures = features.copy()
N_cols= len(labfeatures.columns)
col_list = ['Sales t-' + str(x) for x in range(N_cols,0,-1)]
labfeatures.columns = col_list
# remove rows including zero values