cesar преди 1 ден
родител
ревизия
fc9ae86b2e
променени са 2 файла, в които са добавени 1 реда и са изтрити 349 реда
  1. 1
    1
      v1_multifailure.py
  2. 0
    348
      v1_multifailure_importance_analysis.py

+ 1
- 1
v1_multifailure.py Целия файл

@@ -207,7 +207,7 @@ for i in range(NumberOfFailures+1):
207 207
 
208 208
 print("Threshold : ",threshold)
209 209
 for i in range(NumberOfFailures+1):
210
-    threshold[i]=threshold[i]*1.7
210
+    threshold[i]=threshold[i]*1.3
211 211
 # Threshold is enlarged because, otherwise, for subsamples at 5' have many false positives
212 212
 
213 213
 

+ 0
- 348
v1_multifailure_importance_analysis.py Целия файл

@@ -1,348 +0,0 @@
1
-# Csar Fdez, UdL, 2025
2
-import pandas as pd
3
-import matplotlib.pyplot as plt
4
-import datetime
5
-import numpy as np
6
-import keras
7
-import os.path
8
-import pickle
9
-from keras import layers
10
-from optparse import OptionParser
11
-
12
-
13
-parser = OptionParser()
14
-parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
15
-
16
-(options, args) = parser.parse_args()
17
-
18
-
19
-# data files arrays. Index:
20
-# 0.  No failure
21
-# 1.  Blocked evaporator
22
-# 2.   Full Blocked condenser
23
-# 3.   Partial Blocked condenser
24
-# 4   Fan condenser not working
25
-# 5.  Open door
26
-
27
-
28
-NumberOfFailures=5
29
-NumberOfFailures=4  # So far, we have only data for the first 4 types of failures
30
-datafiles=[]
31
-for i in range(NumberOfFailures+1):
32
-    datafiles.append([])
33
-
34
-# Next set of ddata corresponds to Freezer, SP=-26
35
-datafiles[0]=['2024-08-07_5_','2024-08-08_5_'] 
36
-datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_'] 
37
-datafiles[2]=['2024-12-18_5_','2024-12-19_5_'] 
38
-datafiles[3]=['2024-12-21_5_','2024-12-22_5_','2024-12-23_5_','2024-12-24_5_','2024-12-25_5_','2024-12-26_5_'] 
39
-datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_'] 
40
-#datafiles[4]=[] 
41
-
42
-# Features suggested by Xavier
43
-features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
44
-features=['r1 s1','r1 s2','r1 s3','r1 s4','r1 s5','r1 s6','r1 s7','r1 s8','r1 s9','r1 s10','r2 s1','r2 s2','r2 s3','r2 s4','r2 s5','r2 s6','r2 s7','r2 s8','r2 s9','pa1 apiii','tc s1','tc s2','tc s3']
45
-NumFeatures=len(features)
46
-
47
-df_list=[]
48
-for i in range(NumberOfFailures+1):
49
-    df_list.append([])
50
-
51
-for i in range(NumberOfFailures+1):
52
-    dftemp=[]
53
-    for f in datafiles[i]:
54
-        print("                 ", f)
55
-        #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
56
-        df1 = pd.read_csv('./data/'+f+'.csv')
57
-        dftemp.append(df1)
58
-    df_list[i]=pd.concat(dftemp)
59
-
60
-
61
-# subsampled to 5'  =  30 * 10"
62
-# We consider smaples every 5' because in production, we will only have data at this frequency
63
-subsamplingrate=30
64
-
65
-dataframe=[]
66
-for i in range(NumberOfFailures+1):
67
-    dataframe.append([])
68
-
69
-for i in range(NumberOfFailures+1):
70
-    datalength=df_list[i].shape[0]
71
-    dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
72
-    dataframe[i].reset_index(inplace=True,drop=True)
73
-    dataframe[i].dropna(inplace=True)
74
-
75
-
76
-# Train data is first 2/3 of data
77
-# Test data is: last 1/3 of data 
78
-dataTrain=[]
79
-dataTest=[]
80
-for i in range(NumberOfFailures+1):
81
-    dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
82
-    dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
83
-
84
-
85
-def normalize2(train,test):
86
-    # merges train and test
87
-    means=[]
88
-    stdevs=[]
89
-    for i in range(NumFeatures):
90
-        means.append(train[:,i].mean())
91
-        stdevs.append(train[:,i].std())
92
-    return( (train-means)/stdevs, (test-means)/stdevs )
93
-
94
-dataTrainNorm=[]
95
-dataTestNorm=[]
96
-for i in range(NumberOfFailures+1):
97
-    dataTrainNorm.append([])
98
-    dataTestNorm.append([])
99
-
100
-for i in range(NumberOfFailures+1):
101
-    (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
102
-
103
-def plotData():    
104
-    fig, axes = plt.subplots(
105
-        nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
106
-    )
107
-    for i in range(NumberOfFailures+1):
108
-        axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+",  feature 0")
109
-        axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+",  feature 1")
110
-    #axes[1].legend()
111
-    #axes[0].set_ylabel(features[0])
112
-    #axes[1].set_ylabel(features[1])
113
-    plt.show()
114
-
115
-#plotData()
116
-
117
-
118
-TIME_STEPS = 12
119
-def create_sequences(values, time_steps=TIME_STEPS):
120
-    output = []
121
-    for i in range(len(values) - time_steps + 1):
122
-        output.append(values[i : (i + time_steps)])
123
-    return np.stack(output)
124
-
125
-x_train=[]
126
-for i in range(NumberOfFailures+1):
127
-    x_train.append(create_sequences(dataTrainNorm[i]))
128
-
129
-
130
-model=[]
131
-modelckpt_callback =[]
132
-es_callback =[]
133
-path_checkpoint=[]
134
-for i in range(NumberOfFailures+1):
135
-    model.append([])
136
-    model[i] = keras.Sequential(
137
-        [
138
-            layers.Input(shape=(x_train[i].shape[1], x_train[i].shape[2])),
139
-            layers.Conv1D(
140
-                filters=64,
141
-                kernel_size=7,
142
-                padding="same",
143
-                strides=2,
144
-                activation="relu",
145
-            ),
146
-            layers.Dropout(rate=0.2),
147
-            layers.Conv1D(
148
-                filters=32,
149
-                kernel_size=7,
150
-                padding="same",
151
-                strides=2,
152
-                activation="relu",
153
-            ),
154
-            layers.Conv1DTranspose(
155
-                filters=32,
156
-                kernel_size=7,
157
-                padding="same",
158
-                strides=2,
159
-                activation="relu",
160
-            ),
161
-            layers.Dropout(rate=0.2),
162
-            layers.Conv1DTranspose(
163
-                filters=64,
164
-                kernel_size=7,
165
-                padding="same",
166
-                strides=2,
167
-                activation="relu",
168
-            ),
169
-            layers.Conv1DTranspose(filters=x_train[i].shape[2], kernel_size=7, padding="same"),
170
-        ]
171
-    )
172
-    model[i].compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss="mse")
173
-    model[i].summary()
174
-    path_checkpoint.append("model_v1_"+str(i)+"._checkpoint.weights.h5")
175
-    es_callback.append(keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=15))
176
-    modelckpt_callback.append(keras.callbacks.ModelCheckpoint( monitor="val_loss", filepath=path_checkpoint[i], verbose=1, save_weights_only=True, save_best_only=True,))
177
-
178
-
179
-if options.train:
180
-    history=[]
181
-    for i in range(NumberOfFailures+1):
182
-        history.append(model[i].fit( x_train[i], x_train[i], epochs=400, batch_size=128, validation_split=0.3, callbacks=[  es_callback[i], modelckpt_callback[i]      ],))
183
-
184
-    fig, axes = plt.subplots(
185
-        nrows=int(np.ceil((NumberOfFailures+1)/2)), ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
186
-    )
187
-    for i in range(int(np.ceil((NumberOfFailures+1)/2))):
188
-        for j in range(2):
189
-            r=2*i+j
190
-            if r < NumberOfFailures+1:
191
-                axes[i][j].plot(history[r].history["loss"], label="Training Loss")
192
-                axes[i][j].plot(history[r].history["val_loss"], label="Val Loss")
193
-                axes[i][j].legend()
194
-    plt.show()
195
-else:
196
-    for i in range(NumberOfFailures+1):
197
-        model[i].load_weights(path_checkpoint[i])
198
-
199
-
200
-x_train_pred=[]
201
-train_mae_loss=[]
202
-threshold=[]
203
-for i in range(NumberOfFailures+1):
204
-    x_train_pred.append(model[i].predict(x_train[i]))
205
-    train_mae_loss.append(np.mean(np.abs(x_train_pred[i] - x_train[i]), axis=1))
206
-    threshold.append(np.max(train_mae_loss[i],axis=0))
207
-
208
-print("Threshold : ",threshold)
209
-for i in range(NumberOfFailures+1):
210
-    threshold[i]=threshold[i]*1.7
211
-# Threshold is enlarged because, otherwise, for subsamples at 5' have many false positives
212
-
213
-
214
-#  1st scenario. Detect only anomaly.  Later, we will classiffy it
215
-# Test data=  testnormal + testfail1 + testtail2 + testfail3 + testfail4 + testnormal
216
-d=np.vstack((dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4],dataTestNorm[0]))
217
-
218
-x_test = create_sequences(d)
219
-x_test_pred = model[0].predict(x_test)
220
-test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
221
-
222
-
223
-# Define ranges for plotting in different colors
224
-testRanges=[]
225
-r=dataTestNorm[0].shape[0]
226
-testRanges.append([0,r])
227
-for i in range(1,NumberOfFailures+1):
228
-    rnext=r+dataTestNorm[i].shape[0]
229
-    testRanges.append([r,rnext] )
230
-    r=rnext
231
-testRanges.append([r, x_test.shape[0]  ])
232
-
233
-
234
-def AtLeastOneTrue(x):
235
-    for i in range(NumFeatures):
236
-        if x[i]:
237
-            return True
238
-    return False
239
-
240
-anomalies = test_mae_loss > threshold[0]
241
-anomalous_data_indices = []
242
-for i in range(anomalies.shape[0]):
243
-    if AtLeastOneTrue(anomalies[i]):
244
-    #if anomalies[i][0] or anomalies[i][1] or anomalies[i][2] or anomalies[i][3]:
245
-        anomalous_data_indices.append(i)
246
-
247
-#print(anomalous_data_indices)
248
-
249
-
250
-# Let's plot only a couple of features
251
-def plotData2():    
252
-    fig, axes = plt.subplots(
253
-        nrows=2, ncols=1, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
254
-    )
255
-    axes[0].plot(range(len(x_train[0])),x_train[0][:,0,0],label="normal")
256
-    axes[0].plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,0],label="abnormal")
257
-    axes[0].plot(len(x_train[0])+np.array(anomalous_data_indices),x_test[anomalous_data_indices,0,0],color='red',marker='.',linewidth=0,label="abnormal detection")
258
-    axes[0].legend()
259
-    axes[1].plot(range(len(x_train[0])),x_train[0][:,0,1],label="normal")
260
-    axes[1].plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,1],label="abnormal")
261
-    axes[1].plot(len(x_train[0])+np.array(anomalous_data_indices),x_test[anomalous_data_indices,0,1],color='red',marker='.',linewidth=0,label="abnormal detection")
262
-    axes[1].legend()
263
-    axes[0].set_ylabel(features[0])
264
-    axes[1].set_ylabel(features[1])
265
-    plt.show()
266
-
267
-#plotData2()
268
-
269
-
270
-#   2nd scenario. Go over anomalies and classify it by less error
271
-'''   
272
-#This code works, but too slow
273
-anomalous_data_type=[]
274
-for i in anomalous_data_indices:
275
-    error=[]
276
-    for m in range(1,NumberOfFailures+1):
277
-        error.append(np.mean(np.mean(np.abs(model[m].predict(x_test[i:i+1,:,:])-x_test[i:i+1,:,:]),axis=1)))
278
-    anomalous_data_type.append(np.argmin(error)+1)
279
-'''
280
-
281
-anomalous_data_type=[]
282
-x_test_predict=[]
283
-for m in range(NumberOfFailures+1):
284
-    x_test_predict.append(model[m].predict(x_test))
285
-
286
-
287
-for i in anomalous_data_indices:
288
-    error=[]
289
-    for m in range(1,NumberOfFailures+1):
290
-        error.append(np.mean(np.mean(np.abs(x_test_predict[m][i:i+1,:,:]-x_test[i:i+1,:,:]),axis=1)))
291
-    anomalous_data_type.append(np.argmin(error)+1)
292
-
293
-
294
-# For plotting purposes
295
-
296
-
297
-anomalous_data_indices_by_failure=[]
298
-for i in range(NumberOfFailures+1):
299
-    anomalous_data_indices_by_failure.append([])
300
-
301
-for i in range(len(anomalous_data_indices)):
302
-    print(i," ",anomalous_data_type[i])
303
-    anomalous_data_indices_by_failure[anomalous_data_type[i]].append(anomalous_data_indices[i])  
304
-
305
-
306
-colorline=['violet','lightcoral','cyan','lime','grey']
307
-colordot=['darkviolet','red','blue','green','black']
308
-
309
-featuresToPlot=['r1 s1','r1 s3','r1 s5','r2 s3','r2 s4','pa1 apiii','tc s1','tc s2','tc s3']
310
-indexesToPlot=[]
311
-for i in featuresToPlot:
312
-    indexesToPlot.append(features.index(i))
313
-
314
-def plotData3():
315
-    NumFeaturesToPlot=len(indexesToPlot)
316
-    fig, axes = plt.subplots(
317
-        nrows=NumFeaturesToPlot, ncols=1, figsize=(25, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
318
-    )
319
-    for i in range(NumFeaturesToPlot):
320
-        init=0
321
-        end=len(x_train[0])
322
-        axes[i].plot(range(init,end),x_train[0][:,0,indexesToPlot[i]],label="normal train")
323
-        #axes.plot(range(len(x_train[0]),len(x_train[0])+len(x_test)),x_test[:,0,0],label="abnormal")
324
-        init=end
325
-        end+=testRanges[0][1]
326
-        axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],label="normal test")
327
-        init=end
328
-        end+=(testRanges[1][1]-testRanges[1][0])
329
-        for j in range(1,NumberOfFailures+1):
330
-            axes[i].plot(range(init,end),x_test[testRanges[j][0]:testRanges[j][1],0,indexesToPlot[i]],label="fail type "+str(j), color=colorline[j-1])
331
-            init=end
332
-            end+=(testRanges[j+1][1]-testRanges[j+1][0])
333
-
334
-            axes[i].plot(len(x_train[0])+np.array(anomalous_data_indices_by_failure[j]),x_test[anomalous_data_indices_by_failure[j],0,indexesToPlot[i]],color=colordot[j-1],marker='.',linewidth=0,label="abnormal detection type "+str(j))
335
-
336
-        init=end-(testRanges[NumberOfFailures+1][1]-testRanges[NumberOfFailures+1][0])
337
-        end=init+(testRanges[0][1]-testRanges[0][0])
338
-        axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],color='orange')
339
-
340
-        if i==0:
341
-            axes[i].legend(bbox_to_anchor=(1, 0.5))
342
-        axes[i].set_ylabel(features[indexesToPlot[i]])
343
-        axes[i].grid()
344
-    plt.show()
345
-
346
-
347
-plotData3()
348
-

Powered by TurnKey Linux.