-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDQN.py
2902 lines (2316 loc) · 110 KB
/
DQN.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
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
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 13:03:23 2021
@author: ammar@scch
"""
############################################################################################################
# IMPORTING LIBRARIES
# ##########################################################################################################
import itertools
import time
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import gym
import random
import sklearn.preprocessing
import sklearn.pipeline
import torch
import random
import warnings
import copy
import seaborn as sns
import tensorflow as tf
import tensorflow.keras
import math
from IPython.display import clear_output
from gym import spaces
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines.deepq.policies import LnMlpPolicy, LnCnnPolicy
from stable_baselines import DQN
from stable_baselines.common.env_checker import check_env
from IPython.display import display
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.kernel_approximation import RBFSampler
from sklearn.decomposition import PCA
from lib import plotting
from collections import deque
from sklearn.preprocessing import StandardScaler, MinMaxScaler
warnings.filterwarnings("ignore", category=DeprecationWarning)
standard = StandardScaler()
minmax = MinMaxScaler()
dir_path = os.getcwd()
############################################################################################################
# **********************************************************************************************************
# CASE STUDIES
# **********************************************************************************************************
# ##########################################################################################################
############################################################################################################
# NASA-CMAPSS
# ##########################################################################################################
dataset = 'train_FD002.txt'
df_full = pd.read_csv(dir_path + r'/CMAPSSData/' + dataset, sep=" ", header=None, skipinitialspace=True).dropna(axis=1)
df_full = df_full.rename(columns={0: 'unit', 1: 'cycle', 2: 'W1', 3: 'W2', 4: 'W3'})
# df = df_full
# mapping
train_set = [*range(1, 23), *range(24, 32), *range(33, 39), 40, 44, 45, 46, 49, 51, 53,
*range(55, 61), 62, 63, 64, 66, 67, 69, 70, 71, 74, 78, 81, 88, 94, 97, 102, 103, 105,
106, 107, 108, 118, 120, 128, 133, 136, 137, 141, 165, 173, 176, 178]
test_set = [185, 188, 192, 194, 197, 208, 212, 214, 217, 219, 225, 231, 234, 238, 244, 252, 253, 256, 258, 260]
combined_set = train_set + test_set
df = pd.DataFrame()
for engines in combined_set:
df = pd.concat([df, df_full[df_full['unit'] == engines]], ignore_index=True)
zip_iterator = zip(combined_set, list(range(1, 101)))
mapping_dict = dict(zip_iterator)
df["unit"] = df["unit"].map(mapping_dict)
df_A = df[df.columns[[0, 1]]]
df_W = df[df.columns[[2, 3, 4]]]
df_S = df[df.columns[list(range(5, 26))]]
df_X = pd.concat([df_W, df_S], axis=1)
# RUL as sensor reading
# df_A['RUL'] = 0
# for i in range(1, 101):
# df_A['RUL'].loc[df_A['unit'] == i] = df_A[df_A['unit'] == i].cycle.max() - df_A[df_A['unit'] == i].cycle
# Standardization
df_X = standard.fit_transform(df_X)
# train_test split
engine_unit = 1
'''##
# %% ENGINE UNIT SPECIFIC DATA
engine_unit = 1
engine_df_A = df_A[df_A['unit'] == engine_unit]
engine_df_X = df_X.iloc[engine_df_A.index[0]:engine_df_A.index[-1] + 1]
engine_df_W = df_W.iloc[engine_df_A.index[0]:engine_df_A.index[-1] + 1]
##
# %% NORMALIZE DATA
X = scaler.fit_transform(engine_df_X)
# X = (((engine_df_X - engine_df_X.mean()) / engine_df_X.std()).fillna(0))
# X = ((engine_df_X - engine_df_X.min()) / (engine_df_X.max() - engine_df_X.min())).fillna(0)).values'''
'''
##
# %% READ RUL & APPEND
# df_RUL = pd.read_csv(dir_path + '/CMAPSSData/RUL_FD001.txt', sep=" ", header=None, skipinitialspace=True).dropna(axis=1)
# df_RUL.columns = ['RUL']
# df_z_scaled_RUL = df_z_scaled.join(df_RUL, 1)
##
# %% REGRESSION TO GET "RUL distribution"
# x = df_z_scaled_RUL.iloc[:,list(range(5, 26))]
# y = df_RUL
##
# %% DIMENSIONALITY REDUCTION TO GET "HEALTH INDICATOR"
sensor_data = df_z_scaled.iloc[:, list(range(5, 26))].dropna(axis=1)
pca = PCA(n_components=1)
principalComponents = (1 - pca.fit_transform(sensor_data))
pdf = pd.DataFrame(data=principalComponents, columns=['health indicator'])
pdf_normalized = (pdf - pdf.min()) / (pdf.max() - pdf.min()) * 100
df_scaled_principal = df_z_scaled.join(pdf_normalized, 1)
df_scaled_principal = df_scaled_principal.rename(columns={0: 'engine unit', 1: 'cycle'})
##
# %% VISUALIZATION
engine_unit = 76
engine_df = df_scaled_principal[df_scaled_principal['engine unit'] == engine_unit]
# engine_df.plot.line('cycle', 'health indicator')
# plt.show()
HI = np.array(engine_df['health indicator'])[0:191].astype(np.float32)
# plt.plot(HI)
# plt.show()
'''
############################################################################################################
# HYDRAULIC SYSTEM
# ##########################################################################################################
''''''
# PS1 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS1.txt').mean(axis=1)
# PS2 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS2.txt').mean(axis=1)
# PS3 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS3.txt').mean(axis=1)
# PS4 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS4.txt').mean(axis=1)
# PS5 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS5.txt').mean(axis=1)
# PS6 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\PS6.txt').mean(axis=1)
# EPS1 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\EPS1.txt').mean(axis=1)
# FS1 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\FS1.txt').mean(axis=1)
# FS2 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\FS2.txt').mean(axis=1)
# TS1 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\TS1.txt').mean(axis=1)
# TS2 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\TS2.txt').mean(axis=1)
# TS3 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\TS3.txt').mean(axis=1)
# TS4 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\TS4.txt').mean(axis=1)
# VS1 = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\VS1.txt').mean(axis=1)
# CE = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\CE.txt').mean(axis=1)
# CP = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\CP.txt').mean(axis=1)
# SE = np.loadtxt(r'C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\SE.txt').mean(axis=1)
#
# X = np.array([PS1, PS2, PS3, PS4, PS5, PS6, EPS1, FS1, FS2, TS1, TS2, TS3, TS4, VS1, CE, CP, SE]).T
# np.savetxt(r"C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\sensors.csv", X, delimiter=" ")
# df_X = pd.read_csv(r"C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\sensors.csv", sep=" ", header=None)
# df_X.columns = ['PS1', 'PS2', 'PS3', 'PS4', 'PS5', 'PS6', 'EPS1', 'FS1', 'FS2', 'TS1', 'TS2', 'TS3', 'TS4', 'VS1',
# 'CE', 'CP', 'SE']
#
# df_Y = pd.read_csv(r"C:\Users\abbas\Desktop\case_studies\Datasets\HydraulicSystems\profile.txt", sep="\t", header=None)
# df_Y.columns = ['Cooler_condition', 'Valve_condition', 'Internal_pump_leakage', 'Hydraulic_accumulator', 'stable_flag']
'''fig, ax = plt.subplots()
ax.plot(df_Y['Valve condition'], color='red', label='Valve condition')
ax.tick_params(axis='y', labelcolor='red')
ax.legend(loc="upper right")
ax2 = ax.twinx()
ax2.plot(df_Y['Cooler condition'], color='green', label='Cooler condition')
ax2.tick_params(axis='y', labelcolor='green')
ax2.legend(loc="upper left")
ax3 = ax.twinx()
ax3.plot(df_Y['Internal pump leakage'], color='green', label='Internal pump leakage')
ax3.tick_params(axis='y', labelcolor='green')
ax3.legend(loc="lower right")
ax4 = ax.twinx()
ax4.plot(df_Y['Hydraulic accumulator'], color='blue', label='Hydraulic accumulator')
ax4.tick_params(axis='y', labelcolor='blue')
ax4.legend(loc="lower left")
ax5 = ax.twinx()
ax5.plot(df_Y['stable flag'], color='orange', label='stable flag')
ax5.tick_params(axis='y', labelcolor='orange')
ax5.legend(loc="upper center")
plt.show()'''
############################################################################################################
# YOKOGAWA
# ##########################################################################################################
'''import datetime
df_yoko = pd.read_csv(r'C:/Users/abbas/Desktop/case_studies/Datasets/Yokogawa/CYG-2019-OCT-NOV edited.csv', sep=";")
df_yoko[['Date', 'Time']] = df_yoko['TimeStamp'].str.split(' ', 1, expand=True)
df_yoko['Date'] = pd.to_datetime(df_yoko['Date'], format='%d.%m.%Y')
df_yoko['Time_'] = pd.to_datetime(df_yoko['TimeStamp'])
df_yoko["Month"] = df_yoko["Date"].dt.month
df_yoko["Day"] = df_yoko["Date"].dt.day
df_yoko["Time"] = df_yoko["Time_"].dt.time
df_yoko["Hour"] = df_yoko["Time_"].dt.hour
df_yoko["Minute"] = df_yoko["Time_"].dt.minute
df_yoko["SeverityLevel"] = df_yoko["Severity"] * df_yoko["AlarmLevel"]
df_yoko['Cons'] = df_yoko['TagName'].shift(periods=1)
df_yoko['Cons2'] = df_yoko['TagName'].shift(periods=2)
df_yoko['Cons3'] = df_yoko['TagName'].shift(periods=3)
df_yoko = df_yoko.drop(columns=['SubConditionName', 'TimeStampNS', 'EngUnit', 'StationTimeMilli', 'ItemName', 'Source',
'ModeStatName'])
df_yoko_sub = df_yoko[df_yoko['TagName'] != '025TIC010']
df_yoko_sub = df_yoko_sub[['TimeStamp', 'TagName', 'StationName', 'ConditionName', 'Severity', 'AlarmLevel',
'SeverityLevel', 'AlarmOff', 'AlarmBlink', 'AckRequired', "Month", "Day", "Time",
"Hour", "Minute", 'Cons', 'Cons2', 'Cons3']]
count = df_yoko_sub['Severity'].value_counts()
sort = df_yoko_sub.groupby(["TagName", "Severity"]).size().reset_index(name="Frequency").sort_values(by='Frequency',
ascending=[False])
df_yoko_sub.groupby(["Month", "Day", "Hour"])['TagName'].nunique().reset_index(name="Frequency").sort_values(by='Month')
event = df_yoko_sub.loc[
(df_yoko_sub["Month"] == 11) & (df_yoko_sub["Day"] == 5) & (df_yoko_sub["Time"] == datetime.time(15, 16, 3))]
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(df_yoko_sub.corr(), dtype=bool))
sns.heatmap(df_yoko_sub.corr(), mask=mask)
'''
############################################################################################################
# **********************************************************************************************************
# HIDDEN MARKOV MODEL (LIBRARY)
# **********************************************************************************************************
# ##########################################################################################################
'''from hmmlearn import hmm
from random import randint
import pickle
# df_S = df[df.columns[[6, 8, 11, 12, 15, 16, 19]]]
# df_hmm = pd.concat([df_A['cycle'], df_S], axis=1)
df_hmm = minmax.fit_transform(df_S)
df_hmm = pd.DataFrame(df_hmm)
cols_to_drop = df_hmm.nunique()[df_hmm.nunique() == 1].index
df_hmm = df_hmm.drop(cols_to_drop, axis=1)
cols_to_drop = df_hmm.nunique()[df_hmm.nunique() == 2].index
df_hmm = df_hmm.drop(cols_to_drop, axis=1).to_numpy()
lengths = [df[df['unit'] == i].cycle.max() for i in range(1, df_A['unit'].max() + 1)]
# o = df_X[df_A[df_A['unit'] == 1].index[0]:df_A[df_A['unit'] == 1].index[-1] + 1]
num_states = 15
remodel = hmm.GaussianHMM(n_components=num_states,
n_iter=500,
verbose=True, )
# init_params="cm", params="cmt")
transmat = np.zeros((num_states, num_states))
# Left-to-right: each state is connected to itself and its
# direct successor.
for i in range(num_states):
if i == num_states - 1:
transmat[i, i] = 1.0
else:
transmat[i, i] = transmat[i, i + 1] = 0.5
# Always start in first state
# startprob = np.zeros(num_states)
# startprob[0] = 1.0
# remodel.startprob_ = startprob
# remodel.transmat_ = transmat
remodel.fit(df_hmm, lengths)
# with open("HMM_model.pkl", "wb") as file: pickle.dump(remodel, file)
# with open("filename.pkl", "rb") as file: pickle.load(file)
state_seq = remodel.predict(df_hmm, lengths)
pred = [state_seq[df[df['unit'] == i].index[0]:df[df['unit'] == i].index[-1] + 1] for i in
range(1, df_A['unit'].max() + 1)]
prob = remodel.predict_proba(df_hmm, lengths)
prob_next_step = remodel.transmat_[state_seq, :]
HMM_out = [prob[df[df['unit'] == i].index[0]:df[df['unit'] == i].index[-1] + 1]
for i in range(1, df_A['unit'].max() + 1)]
failure_states = [pred[i][-1] for i in range(df_A['unit'].max())]
# RUL Prediction - Monte Carlo Simulation
from sklearn.utils import check_random_state
transmat_cdf = np.cumsum(remodel.transmat_, axis=1)
random_state = check_random_state(remodel.random_state)
predRUL = []
for i in range(df_A[df_A['unit'] == 1]['cycle'].max()):
RUL = []
for j in range(100):
cycle = 0
pred_obs_seq = [df_hmm[i]]
pred_state_seq = remodel.predict(pred_obs_seq)
while pred_state_seq[-1] not in set(failure_states):
cycle += 1
prob_next_state = (transmat_cdf[pred_state_seq[-1]] > random_state.rand()).argmax()
prob_next_obs = remodel._generate_sample_from_state(prob_next_state, random_state)
pred_obs_seq = np.append(pred_obs_seq, [prob_next_obs], 0)
pred_state_seq = remodel.predict(pred_obs_seq)
RUL.append(cycle)
# noinspection PyTypeChecker
predRUL.append(round(np.mean(RUL)))
plt.plot(predRUL)
plt.plot(df_A[df_A['unit'] == 1].RUL)
plt.show()
plt.figure(0)
plt.plot(pred[0])
plt.plot(pred[1])
plt.plot(pred[2])
plt.xlabel('# Flights')
plt.ylabel('HMM states')
plt.show()
plt.figure(1)
E = [randint(1, df_A['unit'].max()) for p in range(0, 10)]
for e in E:
plt.plot(pred[e - 1])
plt.xlabel('# Flights')
plt.ylabel('HMM states')
plt.legend(E, title='engine unit')
plt.figure(2)
plt.scatter(list(range(1, len(failure_states) + 1)), failure_states)
plt.xlabel('Engine units')
plt.ylabel('HMM states')
plt.legend(title='failure states')
plt.figure(3)
pca = PCA(n_components=2).fit_transform(df_hmm)
for class_value in range(num_states):
# get row indexes for samples with this class
row_ix = np.where(state_seq == class_value)
plt.scatter(pca[row_ix, 0], pca[row_ix, 1])
plt.xlabel('PCA Feature 1')
plt.ylabel('PCA Feature 2')
plt.legend(list(range(0, num_states)), title='HMM states')
plt.show()
import seaborn as sns
sns.heatmap(df_hmm.corr())'''
'''# Generate samples
X, Y = remodel._generate_sample_from_state(np.array([df_X[0]]))
# Plot the sampled data
plt.plot(X[:, 0], X[:, 1], ".-", label="observations", ms=6,
mfc="orange", alpha=0.7)
plt.show()'''
'''
from scipy.stats import multivariate_normal
from sklearn.mixture import GaussianMixture
df_X = PCA(n_components=2).fit_transform(df_X)
gmm = GaussianMixture(n_components=2, n_init=10)
gmm.fit(df_X)
print("using sklearn")
print("best pi : ", gmm.weights_)
print("best mu :", gmm.means_)
# def plot_densities(data, mu, sigma, alpha = 0.5, colors='grey'):
# grid_x, grid_y = np.mgrid[X[:,0].min():X[:,0].max():200j,
# X[:,1].min():X[:,1].max():200j]
# grid = np.stack([grid_x, grid_y], axis=-1)
# for mu_c, sigma_c in zip(mu, sigma):
# plt.contour(grid_x, grid_y, multivariate_normal(mu_c, sigma_c).pdf(grid), colors=colors, alpha=alpha)
def plot_contours(data, means, covs):
"""visualize the gaussian components over the data"""
plt.figure()
plt.plot(data[:, 0], data[:, 1], 'ko')
delta = 0.025
k = means.shape[0]
x = np.arange(-2.5, 10.0, delta)
y = np.arange(-2.5, 10.0, delta)
x_grid, y_grid = np.meshgrid(x, y)
coordinates = np.array([x_grid.ravel(), y_grid.ravel()]).T
col = ['green', 'red', 'indigo', 'yellow', 'blue']
for i in range(k):
mean = means[i]
cov = covs[i]
z_grid = multivariate_normal(mean, cov).pdf(coordinates).reshape(x_grid.shape)
plt.contour(x_grid, y_grid, z_grid, colors=col[i])
plt.tight_layout()
print("check whether the best one converged: ", gmm.converged_)
print("how many steps to convergence: ", gmm.n_iter_)
plot_contours(df_X, gmm.means_, gmm.covariances_)
plt.xlabel("data[:, 0]", fontsize=12)
plt.ylabel("data[:, 1]", fontsize=12)
plt.show()
def E_step(data, pi, mu, sigma):
N = data.shape[0] # number of data-points
K = pi.shape[0] # number of clusters, following notation used before in description
d = mu.shape[1] # dimension of each data point, think of these as attributes
zeta = np.zeros((N, K)) # this is basically responsibility which should be equal to posterior.
for nk in range(K):
zeta[:, nk] = pi[nk] * multivariate_normal.pdf(data, mean=mu[nk], cov=sigma[nk])
# calculate responsibility for each cluster
zeta = zeta / np.sum(zeta, axis=1, keepdims=True)
# use the sum over all the clusters, thus axis=1. Denominator term.
# print ("zeta shape: ", zeta.shape)
return zeta
def M_step(data, zeta):
N, D = data.shape
K = zeta.shape[1] # use the posterior shape calculated in E-step to determine the no. of clusters
pi = np.zeros(K)
mu = np.zeros((K, D))
sigma = np.zeros((K, D, D))
for ik in range(K):
n_k = zeta[:, ik].sum() # we use the definition of N_k
pi[ik] = n_k / N # definition of the weights
elements = np.reshape(zeta[:, ik], (zeta.shape[0], 1))
# get each columns and reshape it (K, 1) form so that later broadcasting is possible.
mu[ik, :] = (np.multiply(elements, data)).sum(axis=0) / n_k
sigma_sum = 0.
for i in range(N):
var = data[i] - mu[ik]
sigma_sum = sigma_sum + zeta[i, ik] * np.outer(var, var) # outer product creates the covariance matrix
sigma[ik, :] = sigma_sum / n_k
return pi, mu, sigma
def elbo(data, zeta, pi, mu, sigma):
N = data.shape[0] # no. of data-points
K = zeta.shape[1] # no. of clusters
d = data.shape[1] # dim. of each object
l = 0.
for i in range(N):
x = data[i]
for k in range(K):
pos_dist = zeta[i, k] # p(z_i=k|x) = zeta_ik
log_lik = np.log(multivariate_normal.pdf(x, mean=mu[k, :], cov=sigma[k, :, :]) + 1e-20) # log p(x|z)
log_q = np.log(zeta[i, k] + 1e-20) # log q(z) = log p(z_i=k|x)
log_pz = np.log(pi[k] + 1e-20) # log p(z_k =1) =\pi _k
l = (l + np.multiply(pos_dist, log_pz) + np.multiply(pos_dist, log_lik) +
np.multiply(pos_dist, -log_q))
# print ("check loss: ", loss)
return l
def train_loop(data, K, tolerance=1e-3, max_iter=500, restart=50):
N, d = data.shape
elbo_best = -np.inf # loss set to the lowest value
pi_best = None
mu_best = None
sigma_best = None
zeta_f = None
for _ in range(restart):
pi = np.ones(K) / K # if 3 clusters then an array of [.33, .33, .33] # the sum of pi's should be one
# that's why normalized
mu = np.random.rand(K, d) # no condition on
sigma = np.tile(np.eye(d), (K, 1, 1)) # to initialize sigma we first start with ones only at the diagonals
# the sigmas are postive semi-definite and symmetric
last_iter_loss = None
all_losses = []
try:
for i in range(max_iter):
zeta = E_step(data, pi, mu, sigma)
pi, mu, sigma = M_step(data, zeta)
l = elbo(data, zeta, pi, mu, sigma)
if l > elbo_best:
elbo_best = l
pi_best = pi
mu_best = mu
sigma_best = sigma
zeta_f = zeta
if last_iter_loss and abs(
(l - last_iter_loss) / last_iter_loss) < tolerance: # insignificant improvement
break
last_iter_loss = l
all_losses.append(l)
except np.linalg.LinAlgError: # avoid the delta function situation
pass
return elbo_best, pi_best, mu_best, sigma_best, all_losses, zeta_f
best_loss, pi_best, mu_best, sigma_best, ls_lst, final_posterior = train_loop(df_X, 5)
'''
############################################################################################################
# **********************************************************************************************************
# HIDDEN MARKOV MODEL 1
# **********************************************************************************************************
# ##########################################################################################################
'''engine_df_A = df_A[df_A['unit'] == engine_unit]
X = df_X[engine_df_A.index[0]:engine_df_A.index[-1] + 1]
class ProbabilityVector:
def __init__(self, probabilities: dict):
states = probabilities.keys()
probs = probabilities.values()
assert len(states) == len(probs)
"The probabilities must match the states."
assert len(states) == len(set(states))
"The states must be unique."
assert abs(sum(probs) - 1.0) < 1e-12
"Probabilities must sum up to 1."
assert len(list(filter(lambda x: 0 <= x <= 1, probs))) == len(probs), \
"Probabilities must be numbers from [0, 1] interval."
self.states = sorted(probabilities)
self.values = np.array(list(map(lambda x:
probabilities[x], self.states))).reshape(1, -1)
@classmethod
def initialize(cls, states: list):
size = len(states)
rand = np.random.rand(size) / (size ** 2) + 1 / size
rand /= rand.sum(axis=0)
return cls(dict(zip(states, rand)))
@classmethod
def from_numpy(cls, array: np.ndarray, states: list):
return cls(dict(zip(states, list(array))))
@property
def dict(self):
return {k: v for k, v in zip(self.states, list(self.values.flatten()))}
@property
def df(self):
return pd.DataFrame(self.values, columns=self.states, index=['probability'])
def __repr__(self):
return "P({}) = {}.".format(self.states, self.values)
def __eq__(self, other):
if not isinstance(other, ProbabilityVector):
raise NotImplementedError
if (self.states == other.states) and (self.values == other.values).all():
return True
return False
def __getitem__(self, state: str) -> float:
if state not in self.states:
raise ValueError("Requesting unknown probability state from vector.")
index = self.states.index(state)
return float(self.values[0, index])
def __mul__(self, other) -> np.ndarray:
if isinstance(other, ProbabilityVector):
return self.values * other.values
elif isinstance(other, (int, float)):
return self.values * other
else:
NotImplementedError
def __rmul__(self, other) -> np.ndarray:
return self.__mul__(other)
def __matmul__(self, other) -> np.ndarray:
if isinstance(other, ProbabilityMatrix):
return self.values @ other.values
def __truediv__(self, number) -> np.ndarray:
if not isinstance(number, (int, float)):
raise NotImplementedError
x = self.values
return x / number if number != 0 else x / (number + 1e-12)
def argmax(self):
index = self.values.argmax()
return self.states[index]
class ProbabilityMatrix:
def __init__(self, prob_vec_dict: dict):
assert len(prob_vec_dict) > 1, \
"The numebr of input probability vector must be greater than one."
assert len(set([str(x.states) for x in prob_vec_dict.values()])) == 1, \
"All internal states of all the vectors must be indentical."
assert len(prob_vec_dict.keys()) == len(set(prob_vec_dict.keys())), \
"All observables must be unique."
self.states = sorted(prob_vec_dict)
self.observables = prob_vec_dict[self.states[0]].states
self.values = np.stack([prob_vec_dict[x].values \
for x in self.states]).squeeze()
@classmethod
def initialize(cls, states: list, observables: list):
size = len(states)
rand = np.random.rand(size, len(observables)) \
/ (size ** 2) + 1 / size
rand /= rand.sum(axis=1).reshape(-1, 1)
aggr = [dict(zip(observables, rand[i, :])) for i in range(len(states))]
pvec = [ProbabilityVector(x) for x in aggr]
return cls(dict(zip(states, pvec)))
@classmethod
def from_numpy(cls, array:
np.ndarray,
states: list,
observables: list):
p_vecs = [ProbabilityVector(dict(zip(observables, x)))
for x in array]
return cls(dict(zip(states, p_vecs)))
@property
def dict(self):
return self.df.to_dict()
@property
def df(self):
return pd.DataFrame(self.values,
columns=self.observables, index=self.states)
def __repr__(self):
return "PM {} states: {} -> obs: {}.".format(
self.values.shape, self.states, self.observables)
def __getitem__(self, observable: str) -> np.ndarray:
if observable not in self.observables:
raise ValueError("Requesting unknown probability observable from the matrix.")
index = self.observables.index(observable)
return self.values[:, index].reshape(-1, 1)
from itertools import product
from functools import reduce
class HiddenMarkovChain:
def __init__(self, T, E, pi):
self.T = T # transmission matrix A
self.E = E # emission matrix B
self.pi = pi
self.states = pi.states
self.observables = E.observables
def __repr__(self):
return "HML states: {} -> observables: {}.".format(
len(self.states), len(self.observables))
@classmethod
def initialize(cls, states: list, observables: list):
T = ProbabilityMatrix.initialize(states, states)
E = ProbabilityMatrix.initialize(states, observables)
pi = ProbabilityVector.initialize(states)
return cls(T, E, pi)
def _create_all_chains(self, chain_length):
return list(product(*(self.states,) * chain_length))
def score(self, observations: list) -> float:
def mul(x, y): return x * y
score = 0
all_chains = self._create_all_chains(len(observations))
for idx, chain in enumerate(all_chains):
expanded_chain = list(zip(chain, [self.T.states[0]] + list(chain)))
expanded_obser = list(zip(observations, chain))
p_observations = list(map(lambda x: self.E.df.loc[x[1], x[0]], expanded_obser))
p_hidden_state = list(map(lambda x: self.T.df.loc[x[1], x[0]], expanded_chain))
p_hidden_state[0] = self.pi[chain[0]]
score += reduce(mul, p_observations) * reduce(mul, p_hidden_state)
return score
class HiddenMarkovChain_FP(HiddenMarkovChain):
def _alphas(self, observations: list) -> np.ndarray:
alphas = np.zeros((len(observations), len(self.states)))
alphas[0, :] = self.pi.values * self.E[observations[0]].T
for t in range(1, len(observations)):
alphas[t, :] = (alphas[t - 1, :].reshape(1, -1)
@ self.T.values) * self.E[observations[t]].T
return alphas
def score(self, observations: list) -> float:
alphas = self._alphas(observations)
return float(alphas[-1].sum())
class HiddenMarkovChain_Simulation(HiddenMarkovChain):
def run(self, length: int) -> (list, list):
assert length >= 0, "The chain needs to be a non-negative number."
s_history = [0] * (length + 1)
o_history = [0] * (length + 1)
prb = self.pi.values
obs = prb @ self.E.values
s_history[0] = np.random.choice(self.states, p=prb.flatten())
o_history[0] = np.random.choice(self.observables, p=obs.flatten())
for t in range(1, length + 1):
prb = prb @ self.T.values
obs = prb @ self.E.values
s_history[t] = np.random.choice(self.states, p=prb.flatten())
o_history[t] = np.random.choice(self.observables, p=obs.flatten())
return o_history, s_history
class HiddenMarkovChain_Uncover(HiddenMarkovChain_Simulation):
def _alphas(self, observations: list) -> np.ndarray:
alphas = np.zeros((len(observations), len(self.states)))
alphas[0, :] = list(self.pi.values()) * self.E[observations[0]].T
for t in range(1, len(observations)):
alphas[t, :] = (alphas[t - 1, :].reshape(1, -1) @ self.T.values) \
* self.E[observations[t]].T
return alphas
def _betas(self, observations: list) -> np.ndarray:
betas = np.zeros((len(observations), len(self.states)))
betas[-1, :] = 1
for t in range(len(observations) - 2, -1, -1):
betas[t, :] = (self.T.values @ (self.E[observations[t + 1]] * betas[t + 1, :].reshape(-1, 1))).reshape(1,
-1)
return betas
def uncover(self, observations: list) -> list:
alphas = self._alphas(observations)
betas = self._betas(observations)
maxargs = (alphas * betas).argmax(axis=1)
return list(map(lambda x: self.states[x], maxargs))
class HiddenMarkovLayer(HiddenMarkovChain_Uncover):
def _digammas(self, observations: list) -> np.ndarray:
L, N = len(observations), len(self.states)
digammas = np.zeros((L - 1, N, N))
alphas = self._alphas(observations)
betas = self._betas(observations)
score = self.score(observations)
for t in range(L - 1):
P1 = (alphas[t, :].reshape(-1, 1) * self.T.values)
P2 = self.E[observations[t + 1]].T * betas[t + 1].reshape(1, -1)
digammas[t, :, :] = P1 * P2 / score
return digammas
class HiddenMarkovModel:
def __init__(self, hml: HiddenMarkovLayer):
self.layer = hml
self._score_init = 0
self.score_history = []
@classmethod
def initialize(cls, states: list, observables: list):
layer = HiddenMarkovLayer.initialize(states, observables)
return cls(layer)
def update(self, observations: list) -> float:
alpha = self.layer._alphas(observations)
beta = self.layer._betas(observations)
digamma = self.layer._digammas(observations)
score = alpha[-1].sum()
gamma = alpha * beta / score
L = len(alpha)
obs_idx = [self.layer.observables.index(x) \
for x in observations]
capture = np.zeros((L, len(self.layer.states), len(self.layer.observables)))
for t in range(L):
capture[t, :, obs_idx[t]] = 1.0
pi = gamma[0]
T = digamma.sum(axis=0) / gamma[:-1].sum(axis=0).reshape(-1, 1)
E = (capture * gamma[:, :, np.newaxis]).sum(axis=0) / gamma.sum(axis=0).reshape(-1, 1)
self.layer.pi = ProbabilityVector.from_numpy(pi, self.layer.states)
self.layer.T = ProbabilityMatrix.from_numpy(T, self.layer.states, self.layer.states)
self.layer.E = ProbabilityMatrix.from_numpy(E, self.layer.states, self.layer.observables)
return score
def train(self, observations: list, epochs: int, tol=None):
self._score_init = 0
self.score_history = (epochs + 1) * [0]
early_stopping = isinstance(tol, (int, float))
for epoch in range(1, epochs + 1):
score = self.update(observations)
print("Training... epoch = {} out of {}, score = {}.".format(epoch, epochs, score))
if early_stopping and abs(self._score_init - score) / score < tol:
print("Early stopping.")
break
self._score_init = score
self.score_history[epoch] = score
# HI = ["0.", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1."]
HI = np.arange(0., 1.1, 0.1)
pi = {0.: 0, 0.1: 0, 0.2: 0, 0.3: 0, 0.4: 0, 0.5: 0, 0.6: 0, 0.7: 0, 0.8: 0, 0.9: 0, 1.: 1}
model = HiddenMarkovModel.initialize(HI, df_X[0:100, 0])
model.layer.pi = pi
model.train(df_X[0:100, 0], epochs=100)
fig, ax = plt.subplots(1, 1, figsize=(10, 5))
ax.semilogy(model.score_history)
ax.set_xlabel('Epoch')
ax.set_ylabel('Score')
ax.set_title('Training history')
plt.grid()
plt.show()'''
############################################################################################################
# **********************************************************************************************************
# HIDDEN MARKOV MODEL 2
# **********************************************************************************************************
# ##########################################################################################################
'''def forward(V, a, b, initial_distribution):
alpha = np.zeros((V.shape[0], a.shape[0]))
alpha[0, :] = initial_distribution * b[:, V[0]]
for t in range(1, V.shape[0]):
for j in range(a.shape[0]):
# Matrix Computation Steps
# ((1x2) . (1x2)) * (1)
# (1) * (1)
alpha[t, j] = alpha[t - 1].dot(a[:, j]) * b[j, V[t]]
return alpha
def backward(V, a, b):
beta = np.zeros((V.shape[0], a.shape[0]))
# setting beta(T) = 1
beta[V.shape[0] - 1] = np.ones((a.shape[0]))
# Loop in backward way from T-1 to
# Due to python indexing the actual loop will be T-2 to 0
for t in range(V.shape[0] - 2, -1, -1):
for j in range(a.shape[0]):
beta[t, j] = (beta[t + 1] * b[:, V[t + 1]]).dot(a[j, :])
return beta
def baum_welch(V, a, b, initial_distribution, n_iter=100):
M = a.shape[0]
T = len(V)
for n in range(n_iter):
alpha = forward(V, a, b, initial_distribution)
beta = backward(V, a, b)
xi = np.zeros((M, M, T - 1))
for t in range(T - 1):
denominator = np.dot(np.dot(alpha[t, :].T, a) * b[:, V[t + 1]].T, beta[t + 1, :])
for i in range(M):
numerator = alpha[t, i] * a[i, :] * b[:, V[t + 1]].T * beta[t + 1, :].T
xi[i, :, t] = numerator / denominator
gamma = np.sum(xi, axis=1)
a = np.sum(xi, 2) / np.sum(gamma, axis=1).reshape((-1, 1))
# Add additional T'th element in gamma
gamma = np.hstack((gamma, np.sum(xi[:, :, T - 2], axis=0).reshape((-1, 1))))
K = b.shape[1]
denominator = np.sum(gamma, axis=1)
for l in range(K):
b[:, l] = np.sum(gamma[:, V == l], axis=1)
b = np.divide(b, denominator.reshape((-1, 1)))
return (a, b)
def viterbi(V, a, b, initial_distribution):
T = V.shape[0]
M = a.shape[0]
omega = np.zeros((T, M))
omega[0, :] = np.log(initial_distribution * b[:, V[0]])
prev = np.zeros((T - 1, M))
for t in range(1, T):
for j in range(M):
# Same as Forward Probability
probability = omega[t - 1] + np.log(a[:, j]) + np.log(b[j, V[t]])
# This is our most probable state given previous state at time t (1)
prev[t - 1, j] = np.argmax(probability)
# This is the probability of the most probable state (2)
omega[t, j] = np.max(probability)
# Path Array
S = np.zeros(T)
# Find the most probable last hidden state
last_state = np.argmax(omega[T - 1, :])
S[0] = last_state
backtrack_index = 1
for i in range(T - 2, -1, -1):
S[backtrack_index] = prev[i, int(last_state)]
last_state = prev[i, int(last_state)]
backtrack_index += 1
# Flip the path array since we were backtracking
S = np.flip(S, axis=0)
# Convert numeric values to actual hidden states
result = []
for s in S:
if s == 0:
result.append("A")
else:
result.append("B")
return result
engine_df_A = df_A[df_A['unit'] == engine_unit]
V = df_X[engine_df_A.index[0]:engine_df_A.index[-1] + 1]
# Transition Probabilities
a = np.ones((30, 30))
a = a / np.sum(a, axis=1)
# Emission Probabilities
b = np.ones((V.shape[0], V.shape[1]))
b = b / np.sum(b, axis=1).reshape((-1, 1))
# Equal Probabilities for the initial distribution
initial_distribution = np.ones((V.shape[1], V.shape[0]))*0.5
a, b = baum_welch(V, a, b, initial_distribution, n_iter=1000)
predicted_observations = np.array((viterbi(V, a, b, initial_distribution)))
print(predicted_observations)'''
############################################################################################################
# **********************************************************************************************************
# INPUT OUTPUT HIDDEN MARKOV MODEL (LIBRARY)
# **********************************************************************************************************