-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAnomaly Detection with LSTM and Cross Correlation Input
2925 lines (2925 loc) · 191 KB
/
Anomaly Detection with LSTM and Cross Correlation Input
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"hide_input": false,
"toc": true
},
"source": [
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n",
"<div class=\"toc\" style=\"margin-top: 1em;\"><ul class=\"toc-item\"><li><span><a href=\"#Imports\" data-toc-modified-id=\"Imports-1\"><span class=\"toc-item-num\">1 </span>Imports</a></span></li><li><span><a href=\"#Data-Prep\" data-toc-modified-id=\"Data-Prep-2\"><span class=\"toc-item-num\">2 </span>Data Prep</a></span><ul class=\"toc-item\"><li><span><a href=\"#Workflow\" data-toc-modified-id=\"Workflow-2.1\"><span class=\"toc-item-num\">2.1 </span>Workflow</a></span></li><li><span><a href=\"#Build-Sqlite-Data-Base\" data-toc-modified-id=\"Build-Sqlite-Data-Base-2.2\"><span class=\"toc-item-num\">2.2 </span>Build Sqlite Data Base</a></span></li><li><span><a href=\"#Clean-Data\" data-toc-modified-id=\"Clean-Data-2.3\"><span class=\"toc-item-num\">2.3 </span>Clean Data</a></span></li><li><span><a href=\"#Create-SVID-Columns\" data-toc-modified-id=\"Create-SVID-Columns-2.4\"><span class=\"toc-item-num\">2.4 </span>Create SVID Columns</a></span></li><li><span><a href=\"#Normalize-Signal-Data\" data-toc-modified-id=\"Normalize-Signal-Data-2.5\"><span class=\"toc-item-num\">2.5 </span>Normalize Signal Data</a></span></li><li><span><a href=\"#Generate-Files-with-Different-Sampling-Rates\" data-toc-modified-id=\"Generate-Files-with-Different-Sampling-Rates-2.6\"><span class=\"toc-item-num\">2.6 </span>Generate Files with Different Sampling Rates</a></span></li><li><span><a href=\"#Calculate-Cross-Correlation-Matrix-(CCM)\" data-toc-modified-id=\"Calculate-Cross-Correlation-Matrix-(CCM)-2.7\"><span class=\"toc-item-num\">2.7 </span>Calculate Cross Correlation Matrix (CCM)</a></span></li><li><span><a href=\"#Shape-SigCCM-Data-for-LSTM-Input\" data-toc-modified-id=\"Shape-SigCCM-Data-for-LSTM-Input-2.8\"><span class=\"toc-item-num\">2.8 </span>Shape SigCCM Data for LSTM Input</a></span></li><li><span><a href=\"#Save-Files\" data-toc-modified-id=\"Save-Files-2.9\"><span class=\"toc-item-num\">2.9 </span>Save Files</a></span><ul class=\"toc-item\"><li><span><a href=\"#Save-Pickled-Files\" data-toc-modified-id=\"Save-Pickled-Files-2.9.1\"><span class=\"toc-item-num\">2.9.1 </span>Save Pickled Files</a></span></li><li><span><a href=\"#Save-to-Dill-File\" data-toc-modified-id=\"Save-to-Dill-File-2.9.2\"><span class=\"toc-item-num\">2.9.2 </span>Save to Dill File</a></span></li><li><span><a href=\"#Save-to-HDF5-File\" data-toc-modified-id=\"Save-to-HDF5-File-2.9.3\"><span class=\"toc-item-num\">2.9.3 </span>Save to HDF5 File</a></span></li><li><span><a href=\"#Save-to-PyArrow-Parquet-File\" data-toc-modified-id=\"Save-to-PyArrow-Parquet-File-2.9.4\"><span class=\"toc-item-num\">2.9.4 </span>Save to PyArrow-Parquet File</a></span></li></ul></li><li><span><a href=\"#Load-Files\" data-toc-modified-id=\"Load-Files-2.10\"><span class=\"toc-item-num\">2.10 </span>Load Files</a></span></li></ul></li><li><span><a href=\"#Data-Generator\" data-toc-modified-id=\"Data-Generator-3\"><span class=\"toc-item-num\">3 </span>Data Generator</a></span><ul class=\"toc-item\"><li><span><a href=\"#Generator-in-a-Python-Class\" data-toc-modified-id=\"Generator-in-a-Python-Class-3.1\"><span class=\"toc-item-num\">3.1 </span>Generator in a Python Class</a></span></li><li><span><a href=\"#Generator-Based-on-Numpy-IO\" data-toc-modified-id=\"Generator-Based-on-Numpy-IO-3.2\"><span class=\"toc-item-num\">3.2 </span>Generator Based on Numpy IO</a></span></li><li><span><a href=\"#Generator-Based-on-HD5-IO\" data-toc-modified-id=\"Generator-Based-on-HD5-IO-3.3\"><span class=\"toc-item-num\">3.3 </span>Generator Based on HD5 IO</a></span></li></ul></li><li><span><a href=\"#LSTM\" data-toc-modified-id=\"LSTM-4\"><span class=\"toc-item-num\">4 </span>LSTM</a></span><ul class=\"toc-item\"><li><span><a href=\"#Build-the-LSTM-Model\" data-toc-modified-id=\"Build-the-LSTM-Model-4.1\"><span class=\"toc-item-num\">4.1 </span>Build the LSTM Model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Step-12,-Sampled-Data,-100-Epochs\" data-toc-modified-id=\"Step-12,-Sampled-Data,-100-Epochs-4.1.1\"><span class=\"toc-item-num\">4.1.1 </span>Step 12, Sampled Data, 100 Epochs</a></span><ul class=\"toc-item\"><li><span><a href=\"#Make-Predictions-and-Plot-ROC-AUC-Metric\" data-toc-modified-id=\"Make-Predictions-and-Plot-ROC-AUC-Metric-4.1.1.1\"><span class=\"toc-item-num\">4.1.1.1 </span>Make Predictions and Plot ROC-AUC Metric</a></span></li></ul></li><li><span><a href=\"#5000-Records-of-Attack-Data,-100-Epochs\" data-toc-modified-id=\"5000-Records-of-Attack-Data,-100-Epochs-4.1.2\"><span class=\"toc-item-num\">4.1.2 </span>5000 Records of Attack Data, 100 Epochs</a></span><ul class=\"toc-item\"><li><span><a href=\"#Make-Predictions-and-Plot-ROC-AUC-Metric\" data-toc-modified-id=\"Make-Predictions-and-Plot-ROC-AUC-Metric-4.1.2.1\"><span class=\"toc-item-num\">4.1.2.1 </span>Make Predictions and Plot ROC-AUC Metric</a></span></li></ul></li></ul></li><li><span><a href=\"#Stacked-LSTMs\" data-toc-modified-id=\"Stacked-LSTMs-4.2\"><span class=\"toc-item-num\">4.2 </span>Stacked LSTMs</a></span><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Make-Predictions-and-Plot-ROC-AUC-Metric\" data-toc-modified-id=\"Make-Predictions-and-Plot-ROC-AUC-Metric-4.2.0.1\"><span class=\"toc-item-num\">4.2.0.1 </span>Make Predictions and Plot ROC-AUC Metric</a></span></li></ul></li></ul></li></ul></li></ul></div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Imports "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np \n",
"import pandas as pd\n",
"import pickle as pkl\n",
"import pyarrow as pa\n",
"import pyarrow.parquet as pq\n",
"import collections\n",
"import itertools\n",
"import keras\n",
"import math\n",
"import h5py\n",
"import os\n",
"\n",
"# os\n",
"from os import mkdir\n",
"\n",
"# pandas\n",
"# from pandas import read_csv \n",
"# from pandas import datetime \n",
"from pandas.plotting import autocorrelation_plot\n",
"\n",
"# scipy\n",
"from scipy import sparse\n",
"from scipy import signal\n",
"from scipy.signal import correlate\n",
"from scipy.signal import correlate2d\n",
"from scipy.sparse import coo_matrix, vstack\n",
"\n",
"# statsmodels\n",
"# from statsmodels.tsa.arima_model import ARIMA \n",
"\n",
"# sci-kit learn\n",
"from sklearn.metrics import auc\n",
"from sklearn.metrics import roc_curve\n",
"from sklearn.metrics import mean_squared_error\n",
"from sklearn.datasets import make_classification\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# matplotlib\n",
"from matplotlib import pyplot as plt\n",
"\n",
"# sqlite\n",
"# from sqlalchemy import create_engine\n",
"# from flask.ext.sqlalchemy import SQLAlchemy\n",
"# from flask_sqlalchemy import SQLAlchemy\n",
"# from sqlalchemy import create_engine\n",
"\n",
"# sci-kit learn\n",
"# from sklearn.decomposition import PCA\n",
"from sklearn.metrics import mean_squared_error\n",
"from sklearn.preprocessing import MinMaxScaler\n",
"\n",
"# keras\n",
"from keras.preprocessing.sequence import pad_sequences\n",
"from keras.callbacks import EarlyStopping\n",
"from keras.layers import TimeDistributed\n",
"from keras.models import Sequential\n",
"from keras.models import Model\n",
"from keras.layers import Dense\n",
"from keras.layers import LSTM"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data Prep"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Workflow \n",
" \n",
"1. Extract Data on TORGI\n",
" * Table join on jupyterhub to merge AGC, CN0 and local timestamp info\n",
" * Generate CSV file\n",
"2. Build Sqlite Data Base\n",
" * Read CSV file and load into sqlite db in chunks to avoid using enormous CSV files and make data more accessible\n",
"3. Clean Data\n",
" * Load dataframe, change time stamps to 64 bit integers\n",
" * Sort data by local time \n",
" * Reindex dataframe\n",
" * Remove NaN Values from Attack Column\n",
"4. Data Wrangling\n",
" * Limit Data to Days with Jamming\n",
" * Create SVID Columns, one for each AGC & CN0 signal\n",
" * Normalize Signal Data\n",
" * Generate files with different sampling rates\n",
" (because memory is a **_huge_** problem).\n",
"5. Number Crunching and More Data Wrangling\n",
" * Select various lookahead time windows in which to do Cross Correlation\n",
" * Calculate normalized Cross Correlation Matrix (CCM) \n",
" * Flatten CCM and append to each row in separate column\n",
"6. Shape SigCCM Data for LSTM Input (i.e. more Data Wrangling)\n",
" * In addition to the CCM time window, create time sequence windows for the LSTM\n",
" * Wrangle data, converting column with CCMs into a column of nested sequences of CCMs of predetermined length. With 5,000 records of jamming data, this produces a huge 20GB file\n",
"7. Store LSTM-Ready Data in HDF5 for Use by Data Generators \n",
"8. Create Data Generator that can feed chunks of the 20GB file into Keras, batch by batch\n",
"9. Define various LSTM models"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1.2.0'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"scipy.__version__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Build Sqlite Data Base"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"filepath = 'CSV Files/combined.csv'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# csv_database = create_engine('sqlite:///csv_database.db')\n",
"csv_database = create_engine('sqlite:///combined.db')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"chunksize = 100000\n",
"i, j = 0, 1\n",
"for df in pd.read_csv(filepath, chunksize=chunksize, iterator=True):\n",
" df = df.rename(columns={c: c.replace(' ', '_') for c in df.columns}) \n",
" # shift up all index values by j\n",
" df.index += j\n",
" i += 1\n",
" df.to_sql('table', csv_database, if_exists='append')\n",
" # take highest index value and add one\n",
" # (don't know the index of the highest index, so use -1)\n",
" j = df.index[-1] + 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NOTE: Sqlite apparently requires you to put the table name between quotes. See this [Stackoverflow article](https://stackoverflow.com/questions/25387537/inserting-a-table-name-into-a-query-gives-sqlite3-operationalerror-near-sy)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# id, svid, constellation, cn0, agc, has_agc, sat_time_nanos\n",
"# fields = \"id, svid, constellation, cn0, agc, has_agc, sat_time_nanos\"\n",
"# fields = \"constellation, cn0, agc, has_agc, sat_time_nanos\"\n",
"# fields = \"cn0, agc\"\n",
"# sql_string = 'SELECT ' + fields + ' FROM table'\n",
"# sql_string = 'SELECT * FROM \"table\" LIMIT 5'\n",
"flds = \"svid, constellation, cn0, agc, local_time, sat_time_nanos, attack\"\n",
"sql_string = 'SELECT ' + flds + ' FROM \"table\"'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_combined = pd.read_sql_query(sql_string, csv_database)\n",
"\n",
"df_combined[df_combined[\"Attack\"] == 1].count()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Clean Data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Convert Time Stamps and SVID from Float to 64bit Integer"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"sat_time_nanos = df_combined[\"sat_time_nanos\"]\n",
"localtime = df_combined[\"local_time\"]\n",
"svids = df_combined[\"svid\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"sat_time_nanos = sat_time_nanos.astype('int64')\n",
"localtime = localtime.astype('int64') \n",
"svids = svids.astype('int64')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_combined[\"sat_time_nanos\"] = sat_time_nanos\n",
"df_combined[\"local_time\"] = localtime\n",
"df_combined[\"svid\"] = svids"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sort Data by Local Time Stamp and Reindex"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# colheader = 'sat_time_nanos'\n",
"colheader = 'local_time'\n",
"df_combined_sorted = df_combined.sort_values(colheader).copy()\n",
"df_combined_sorted.index = range(len(df_combined_sorted))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remove NaN Values from Attack Column"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"values = {\"Attack\": False}\n",
"df_combined_sorted = df_combined_sorted.fillna(value = values)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_combined_sorted[\"Attack\"].value_counts()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Limit Days to Days with Jamming.\n",
"\n",
"Reasoning:\n",
"* Assuming this will probably not cause data imbalance, based on Tracey's statement that pervasive jamming might represent actual conditions and \n",
"* We don't know how to label much of the data we have. We cannot assume the absence of a True Attack label means Attack = False necessarily. \n",
"\n",
"Hao's calculated range of local time stamps on jamming days:\n",
"* local time for 10/3/2018 00:00 is 1538264040000 \n",
"* local time for 10/6/2018 00:00 is 1538523240000 "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"(df_combined_sorted[\"local_time\"].min(), \n",
" df_combined_sorted[\"local_time\"].max())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_jamming = df_combined_sorted[\n",
" df_combined_sorted[\"local_time\"] >= 1538264040000 # 1538264040000 \n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_jamming = df_combined_sorted[\n",
" df_combined_sorted[\"local_time\"] >= 0 # 1538264040000 \n",
"]\n",
"df_jamming[\"Attack\"].value_counts()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_jamming = df_jamming[\n",
" (df_jamming[\"local_time\"] <= 1538523240000) # 1538523240000\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create SVID Columns"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def get_headers(df): \n",
" \n",
" svids = df[\"svid\"].unique()\n",
" svids = list(svids)\n",
"\n",
" svidhdrs = []\n",
" \n",
" # create separate AGC & CN0 labels for each\n",
" # of the 106 AGC & CN0 signals.\n",
" for svid in svids: \n",
" agc_nm = \"agc_\" + \"{:003d}\".format(svid) \n",
" cn0_nm = \"cn0_\" + \"{:003d}\".format(svid) \n",
" svidhdrs.append(agc_nm)\n",
" svidhdrs.append(cn0_nm)\n",
"\n",
" svidhdrs.sort()\n",
"\n",
" # Since we have separate AGC & CN0 signals for\n",
" # each of the 106 signals, eliminate the original\n",
" # AGC & CN0 labels (without number suffixes)\n",
" dfcols = list(df.columns)\n",
" dfcols.remove('svid')\n",
" dfcols.remove('cn0')\n",
" dfcols.remove('agc') \n",
" dfcols.remove('constellation')\n",
" dfcols.remove('sat_time_nanos') \n",
" \n",
" colhdrs = dfcols + svidhdrs\n",
" \n",
" # Return signal IDs and (new) revised column headers\n",
" return svids, colhdrs"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def create_svid_cols(df):\n",
"\n",
" svids, colhdrs = get_headers(df) \n",
" df_new = pd.DataFrame(columns = colhdrs)\n",
" # Create a first row of zeros\n",
" d = {k:0 for k in colhdrs} \n",
" df_new.loc[0] = d # first row\n",
" \n",
" lt_previous = -1 \n",
" \n",
" for rowidx, row in df.iterrows():\n",
" \n",
" svid = row[\"svid\"] \n",
" agc_nm = \"agc_\" + \"{:003d}\".format(svid) \n",
" cn0_nm = \"cn0_\" + \"{:003d}\".format(svid) \n",
"\n",
" lt = row[\"local_time\"]\n",
" \n",
" if lt != lt_previous and lt_previous != -1:\n",
" \n",
" # new time stamp\n",
" \n",
" # open up a new row in dataframe\n",
" nrow = len(df_new)\n",
" \n",
" # initialize new row to have same values as last row\n",
" lastrow = df_new.loc[nrow - 1].to_dict()\n",
" df_new.loc[nrow] = lastrow\n",
" \n",
" else:\n",
" # load data into current (already existing) last row\n",
" nrow = len(df_new) - 1\n",
" \n",
" df_new.loc[nrow][agc_nm] = row[\"agc\"]\n",
" df_new.loc[nrow][cn0_nm] = row[\"cn0\"]\n",
" df_new.loc[nrow][\"Attack\"] = row[\"Attack\"]\n",
" df_new.loc[nrow][\"local_time\"] = lt \n",
" \n",
" lt_previous = lt\n",
" \n",
" return df_new"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_signals = create_svid_cols(df_jamming)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pickle the result."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"path = PickledDir + \"df_signals.pkl\"\n",
"fd = open(path, \"wb\")\n",
"pkl.dump(df_signals, fd)\n",
"fd.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Normalize Signal Data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Do the signal values need to be normalized?\n",
"\n",
"Take a peak at max signal values to find out."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"local_time 1.538464e+12\n",
"Attack 1.000000e+00\n",
"agc_001 1.711000e+01\n",
"agc_002 3.270000e+00\n",
"agc_003 3.160000e+01\n",
"agc_004 3.368000e+01\n",
"agc_005 3.368000e+01\n",
"agc_006 3.368000e+01\n",
"agc_007 3.368000e+01\n",
"agc_008 2.203000e+01\n",
"dtype: float64"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data_cols = list(df_signals.columns)\n",
"\n",
"df_signals[data_cols].max()[:10]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def normalize_signals(df):\n",
" \n",
" # initialize scaler object\n",
" scaler = MinMaxScaler(feature_range=(0, 1))\n",
" \n",
" # extract column names and remove \n",
" # those that are irrelevant \n",
" data_cols = list(df_signals_in_cols.columns)\n",
" data_cols.remove(\"local_time\")\n",
" data_cols.remove(\"Attack\")\n",
" \n",
" # extract signal values\n",
" vals = df[data_cols].values\n",
" vals = vals.astype('float32')\n",
" vals_norm = scaler.fit_transform(vals)\n",
" \n",
" df_norm = df.copy()\n",
" for idx, colname in enumerate(data_cols):\n",
" df_norm[colname] = vals_norm[:, idx]\n",
"\n",
" return df_norm"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_norm = normalize_signals(df_signals)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pickle the result."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"path = PickledDir + \"df_norm.pkl\"\n",
"fd = open(path, \"wb\")\n",
"pkl.dump(df_norm, fd)\n",
"fd.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generate Files with Different Sampling Rates"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Filter DataFrame, selecting every *samplerate* rows (records)\n",
"def samplerecords(df, samplerate):\n",
"\n",
" indices = list(range(0, len(df), samplerate)) \n",
" df_filtered = df.iloc[indices]\n",
" \n",
" return df_filtered"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2713, 90)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_attack_step12 = samplerecords(df_norm_attackperiod, 12)\n",
"df_attack_step12.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Go ahead and reindex this (sparsely sampled) dataframe."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_attack_step12.index = range(len(df_attack_step12))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plots of labels VS. local time."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x7ff9e1f92908>]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAD8CAYAAACMwORRAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAH+NJREFUeJzt3XuYXXV97/H3d26ZJOQCzORCbhOSAAkRuYwQA9VQogY8B9RDzwMtFSwWHy1aqz2neLSK2NbWtqfP41OqcizeTgWRWo02NiKiWI5cJiCXCUSGhCRDIJmQy+SeTOZ7/tgryc6ePbPXzF5rr8t8Xs+TzN5rr1m/7/qttb977bW+81vm7oiISL7UJR2AiIhET8ldRCSHlNxFRHJIyV1EJIeU3EVEckjJXUQkh5TcRURySMldRCSHlNxFRHKoIamGW1pavK2tLanmRUQyac2aNdvdvbXSfIkl97a2Njo6OpJqXkQkk8xsY5j5dFpGRCSHlNxFRHJIyV1EJIeU3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fyRmb1liHkHuzn3cKdHoVzcXwLmAedT2Jn+Ppg3TXE3ABcCX3L3C4B9FE4HDCYLsWeh3wsBFc7vXg18t9Ksg8SSSOxl4k59nwcfONdQOJVyBjCewvt1sPZSE/twpTK5u/uW4Oc24N8ofNXZGnzNJPi5LZi9G5hV9OszgS0Vps8sMz2WuN19q7sfdfd+4P8E6zKSuLdT+BreUDI9Ct1At7s/Fjy/n0LCTH2fDxZ7Rvr9mCuBJ919a/A8C/0+IO6M9PlyYIO797j7EeB7wNIh2jseY/D6JAq3Eh3uOtVc6pK7mY03swnHHgNvB57j5Jtw3wj8IHi8EnhvUEmwBNgdfJVdDbzdzE4NPq3fDqwOXttjZkuCc2fvLVpW5HEfe5MG3h2sy7G4rwuuxs8FFlC4+FX2huTBOdOHKNyAvLQPquLurwGbzezsYNIVwFpS3udDxZ6Ffi9yPSef2kh9v5eLOyN9vglYYmbjgj45tq8P1l7xtrgW+FkQ37DWKaLYhyfuK7bD/UfhHOrTwb9O4JPB9NOBB4EXg5+nBdMNuJPCFepngfaiZf0BhQsdXcD7iqa3U9jxXgL+keCPuWKK+1tBXM9Q2MjTi37nk0EM6yiqYqBQFfGb4LVPlrTxeLA+3wXGRNjv5wMdQZzfp1B1keo+rxB7Vvp9HPA6MKloWur7fZC4s9LnnwVeCPrlWxQqXsq2BzQHz7uC188c6TrV+p/+QlVEJIdSd1pGRESqp+QuIpJDSu4iIjmk5C4ikkNK7iIiOaTkLiKSQ0ruIiI5pOQuIpJD/x905id2WGMuMQAAAABJRU5ErkJggg==\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.plot(df_attack_step12.index,\n",
" df_attack_step12[\"Attack\"])"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x7f17265b28d0>]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
},
{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Kw+KSJnYMN/N6r6/wD8LICvIzbqLwB4EAP/zaybca+0EPdQEJFXAPjvAP65qn6naFfLNm2wvfeIyA8CeE5VH0xvtuyqJZ8N7rtB7J1eDODnVfUiAH+BOAyTx0Z8N0mO4QDiUMp3AzgDwDWWXQf1m1k3434MwO7U+10AnlnRXDpFREaIDfuvqupvJJu/mTwaI/n7uWR73vdStH2XZfs6cBmA60Tka4gff78fsSd/VvLIDcxfz/Q7SD5/FeKlIOt+Z+vAMQDHVPX+5P3diI39pv9urgTwpKoeV9UxgN8A8H0Y+G9m3Yx7lcW6154kvvcpAI+q6kdTH6UXIr8RwOdT29+dVD9cCuCF5PH7MIB3isjZiffyTgCHk89eFJFLk3O9OzVWr1HVD6rqLlXdg/jf/7dV9YcB3IN4cXZg8buxLd5+EMD1SWXEXgD7ECcL1/Y3pqrfAPC0iPyVZNMVAB4BfzdfB3CpiLw8mbf5Xob9m1l1RrfuH8QZ/scQZ6c/tOr5dHSNfwvxY91DAL6S/LkWcdzvtwA8nvx9TrK/ALg9+U7+GMBWaqwfQZz42Qbw3tT2LQBfTY75r0ga2tbpD4DLMauWuRDxf7RtAL8O4LRk++nJ++3k8wtTx38ouf6jSFV9rPNvDMBfB3Ak+e38JuJql43/3QD4dwD+JJn7ZxBXvAz6N8MOVUIIGSDrFpYhhBBSARp3QggZIDTuhBAyQGjcCSFkgNC4E0LIAKFxJ4SQAULjTgghA4TGnRBCBsj/B00zkSlqb6/ZAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.plot(df_norm_step1000.index,\n",
" df_norm_step1000[\"Attack\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Calculate Cross Correlation Matrix (CCM)\n",
"\n",
"Calculate the cross correlation matrix on a sliding time window and append the contents of the ccm to the signal data."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def mycorrelate(ar_signals, normalized = False):\n",
" \n",
" # initialize cross correlation matrix with zeros\n",
" nrows = ar_signals.shape[0] \n",
" ccm = np.zeros(shape=(nrows, nrows), dtype=list)\n",
" \n",
" for i, outer_row in enumerate(ar_signals):\n",
" for j, inner_row in enumerate(ar_signals): \n",
"\n",
" if(not normalized):\n",
" x = np.correlate(inner_row, outer_row) \n",
" else: \n",
" len_inner = int(len(inner_row))\n",
" mean_inner = np.mean(inner_row)\n",
" std_inner = np.std(inner_row)\n",
" a = (inner_row - mean_inner) / (std_inner * len_inner) \n",
" b = (outer_row - np.mean(outer_row)) / (\n",
" np.std(outer_row)) \n",
" x = np.correlate(a, b) \n",
" \n",
" ccm[i][j] = x[0] \n",
" \n",
" return ccm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**concat_ccm**\n",
"\n",
"* Look ahead the number of time slices specified in window parameter _win_ \n",
"* Take the cross correlation matrix (CCM) in the window of all signals.\n",
"* Flatten each CCM into a single (nested 2D) list\n",
"* Each row will have a flatted CCM. Store it in the **sigccm** column."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#############################################################\n",
"# concat_ccm: \n",
"# Description: Takes DataFrame of signals as input \n",
"# and concatenates a flattened ccm onto each row,\n",
"# but unlike prior version of this routine, concat_ccm\n",
"# will save the results at regular intervals as a precaution.\n",
"#############################################################\n",
"\n",
"def concat_ccm(df, win, batchID, batch_size):\n",
"\n",
" DataDir = \"data/\"\n",
" BatchDir = DataDir + batchID + \"/\" \n",
"\n",
" # If directory does not already exist\n",
" # for this batch, create it.\n",
" if not os.path.isdir(BatchDir):\n",
" mkdir(BatchDir) \n",
" \n",
" result = [] \n",
" width = df.shape[1]\n",
" length = df.shape[0]\n",
" \n",
" # Isolate signal columns in order to calculate CCM\n",
" value_cols = list(df.columns)\n",
" value_cols.remove(\"local_time\")\n",
" value_cols.remove(\"Attack\")\n",
" \n",
" df_values = df[value_cols]\n",
" \n",
" # Cross correlation matrix (ccm) will be a \n",
" # square matrix of dimensions (win X win)\n",
" \n",
" # Length of augmented row will be:\n",
" # length of current row + flattened ccm (win X win) \n",
" # First win-1 rows will be extended by zeros\n",
" for i in range(win - 1):\n",
" row = list(df_values.iloc[i].values)\n",
" zeros = np.zeros(win * win).tolist()\n",
" result.append(row + zeros)\n",
" \n",
" for idx, _ in enumerate(df_values.iterrows()):\n",
" \n",
" if idx + win > length:\n",
" break\n",
"\n",
" view = df_values.iloc[idx : idx + win].values \n",
" ccm = mycorrelate(view, normalized = True)\n",
" \n",
" flatmatrix = ccm.ravel().tolist()\n",
"\n",
" # Attach the flattened CCM to the **end** of the window\n",
" # (Careful: indices change within the view)\n",
" # Last line of view will always have index of win - 1\n",
" concatenated_line = list(view[win - 1, :]) + flatmatrix \n",
" result.append(concatenated_line)\n",
" \n",
" if idx != 0 and idx % batch_size == 0:\n",
" \n",
" fnm = 'df_{:s}_id{:d}.pkl'.format(batchID, idx)\n",
" \n",
" df_view = df.iloc[0 : idx + win].copy() \n",
" df_view[\"sigccm\"] = pd.Series(result).values\n",
"\n",
" df_view[\"sigccm\"] = df_view.sigccm.apply(\n",
" lambda x: [list(x)])\n",
" \n",
" # reindex output DataFrame\n",
" df_view.index = range(len(df_view))\n",
"\n",
" path = BatchDir + fnm\n",
" fd = open(path, \"wb\")\n",
" pkl.dump(df_view, fd)\n",
" fd.close()\n",
"\n",
" df_augmented = df.copy()\n",
" df_augmented[\"sigccm\"] = pd.Series(result).values\n",
" \n",
" # Column \"sigccm\" now contains list elements.\n",
" # Encapsulate each list element with an extra set\n",
" # of list brackets to set the stage for creating\n",
" # a list of lists that represents the time steps\n",
" # of an LSTM\n",
" \n",
" df_augmented[\"sigccm\"] = df_augmented.sigccm.apply(\n",
" lambda x: [list(x)])\n",
"\n",
" # reindex output DataFrame\n",
" df_augmented.index = range(len(df_augmented))\n",
" \n",
" return df_augmented, result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate SigCCM Training Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_augmented, res = concat_ccm(df_norm_attackperiod, \n",
" win = 100,\n",
" batchID = \"norm_attack\",\n",
" batch_size = 1000)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"df_augmented, res = concat_ccm(df_attack_step12, \n",
" win = 100,\n",
" batchID = \"attack_step12\",\n",
" batch_size = 1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Split SigCCM data into train and test sets."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"length = len(df_augmented)\n",
"len_train = int(length * 0.9)\n",
"len_test = length - len_train\n",
"df_sigccm_train = df_augmented[ : len_train]\n",
"df_sigccm_test = df_augmented[len_train : length]\n",
"# reindex the test data\n",
"df_sigccm_test.index = range(len(df_sigccm_test))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate SigCCM Test Data for `id_attack_5000` from separate dataset."