Bez popisu

v1.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. parser = OptionParser()
  12. parser.add_option("-t", "--train", dest="train", help="Trains the models (false)", default=False, action="store_true")
  13. (options, args) = parser.parse_args()
  14. # data files arrays. Index:
  15. # 0. No failure
  16. # 1. Blocked evaporator
  17. # 2. Full Blocked condenser
  18. # 3. Partial Blocked condenser
  19. # 4 Fan condenser not working
  20. # 5. Open door
  21. NumberOfFailures=5
  22. NumberOfFailures=4 # So far, we have only data for the first 4 types of failures
  23. datafiles=[]
  24. for i in range(NumberOfFailures+1):
  25. datafiles.append([])
  26. # Next set of ddata corresponds to Freezer, SP=-26
  27. datafiles[0]=['2024-08-07_5_','2024-08-08_5_']
  28. datafiles[1]=['2024-12-11_5_', '2024-12-12_5_','2024-12-13_5_','2024-12-14_5_','2024-12-15_5_']
  29. datafiles[2]=['2024-12-18_5_','2024-12-19_5_']
  30. 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_']
  31. datafiles[4]=['2024-12-28_5_','2024-12-29_5_','2024-12-30_5_','2024-12-31_5_','2025-01-01_5_']
  32. #datafiles[4]=[]
  33. # Features suggested by Xavier
  34. # Care with 'tc s3' because on datafiles[0] is always nulll
  35. # Seems to be incoropored in new tests
  36. features=['r1 s1','r1 s4','r1 s5','pa1 apiii']
  37. 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']
  38. #features=['r2 s2', 'tc s1','r1 s10','r1 s6','r2 s8']
  39. NumFeatures=len(features)
  40. df_list=[]
  41. for i in range(NumberOfFailures+1):
  42. df_list.append([])
  43. for i in range(NumberOfFailures+1):
  44. dftemp=[]
  45. for f in datafiles[i]:
  46. print(" ", f)
  47. #df1 = pd.read_csv('./data/'+f+'.csv', parse_dates=['datetime'], dayfirst=True, index_col='datetime')
  48. df1 = pd.read_csv('./data/'+f+'.csv')
  49. dftemp.append(df1)
  50. df_list[i]=pd.concat(dftemp)
  51. # subsampled to 5' = 30 * 10"
  52. # We consider smaples every 5' because in production, we will only have data at this frequency
  53. subsamplingrate=30
  54. dataframe=[]
  55. for i in range(NumberOfFailures+1):
  56. dataframe.append([])
  57. for i in range(NumberOfFailures+1):
  58. datalength=df_list[i].shape[0]
  59. dataframe[i]=df_list[i].iloc[range(0,datalength,subsamplingrate)][features]
  60. dataframe[i].reset_index(inplace=True,drop=True)
  61. dataframe[i].dropna(inplace=True)
  62. # Train data is first 2/3 of data
  63. # Test data is: last 1/3 of data
  64. dataTrain=[]
  65. dataTest=[]
  66. for i in range(NumberOfFailures+1):
  67. dataTrain.append(dataframe[i].values[0:int(dataframe[i].shape[0]*2/3),:])
  68. dataTest.append(dataframe[i].values[int(dataframe[i].shape[0]*2/3):,:])
  69. def normalize2(train,test):
  70. # merges train and test
  71. means=[]
  72. stdevs=[]
  73. for i in range(NumFeatures):
  74. means.append(train[:,i].mean())
  75. stdevs.append(train[:,i].std())
  76. return( (train-means)/stdevs, (test-means)/stdevs )
  77. dataTrainNorm=[]
  78. dataTestNorm=[]
  79. for i in range(NumberOfFailures+1):
  80. dataTrainNorm.append([])
  81. dataTestNorm.append([])
  82. for i in range(NumberOfFailures+1):
  83. (dataTrainNorm[i],dataTestNorm[i])=normalize2(dataTrain[i],dataTest[i])
  84. def plotData():
  85. fig, axes = plt.subplots(
  86. nrows=NumberOfFailures+1, ncols=2, figsize=(15, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  87. )
  88. for i in range(NumberOfFailures+1):
  89. axes[i][0].plot(np.concatenate((dataTrainNorm[i][:,0],dataTestNorm[i][:,0])),label="Fail "+str(i)+", feature 0")
  90. axes[i][1].plot(np.concatenate((dataTrainNorm[i][:,1],dataTestNorm[i][:,1])),label="Fail "+str(i)+", feature 1")
  91. #axes[1].legend()
  92. #axes[0].set_ylabel(features[0])
  93. #axes[1].set_ylabel(features[1])
  94. #plt.show()
  95. #plotData()
  96. NumFilters=64
  97. KernelSize=7
  98. DropOut=0.1
  99. ThresholdFactor=1.7
  100. TIME_STEPS = 48 # This is a trade off among better performance (high) and better response delay (low)
  101. def create_sequences(values, time_steps=TIME_STEPS):
  102. output = []
  103. for i in range(len(values) - time_steps + 1):
  104. output.append(values[i : (i + time_steps)])
  105. return np.stack(output)
  106. x_train=[]
  107. for i in range(NumberOfFailures+1):
  108. x_train.append(create_sequences(dataTrainNorm[i]))
  109. # Reused code from v1_multifailure for only one model. No classification
  110. #for i in range(NumberOfFailures+1):
  111. model = keras.Sequential(
  112. [
  113. layers.Input(shape=(x_train[0].shape[1], x_train[0].shape[2])),
  114. layers.Conv1D(
  115. filters=NumFilters,
  116. kernel_size=7,
  117. padding="same",
  118. strides=2,
  119. activation="relu",
  120. ),
  121. layers.Dropout(rate=DropOut),
  122. layers.Conv1D(
  123. filters=int(NumFilters/2),
  124. kernel_size=KernelSize,
  125. padding="same",
  126. strides=2,
  127. activation="relu",
  128. ),
  129. layers.Conv1DTranspose(
  130. filters=int(NumFilters/2),
  131. kernel_size=KernelSize,
  132. padding="same",
  133. strides=2,
  134. activation="relu",
  135. ),
  136. layers.Dropout(rate=DropOut),
  137. layers.Conv1DTranspose(
  138. filters=NumFilters,
  139. kernel_size=KernelSize,
  140. padding="same",
  141. strides=2,
  142. activation="relu",
  143. ),
  144. layers.Conv1DTranspose(filters=x_train[i].shape[2], kernel_size=KernelSize, padding="same"),
  145. ]
  146. )
  147. model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss="mse")
  148. model.summary()
  149. path_checkpoint="model_noclass_v1_checkpoint.weights.h5"
  150. es_callback=keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=15)
  151. modelckpt_callback=keras.callbacks.ModelCheckpoint( monitor="val_loss", filepath=path_checkpoint, verbose=1, save_weights_only=True, save_best_only=True,)
  152. if options.train:
  153. history=model.fit( x_train[0], x_train[0], epochs=400, batch_size=128, validation_split=0.3, callbacks=[ es_callback, modelckpt_callback ],)
  154. else:
  155. model.load_weights(path_checkpoint)
  156. x_train_pred=model.predict(x_train[0])
  157. train_mae_loss=np.mean(np.abs(x_train_pred - x_train[0]), axis=1)
  158. threshold=np.max(train_mae_loss,axis=0)
  159. print("Threshold : ",threshold)
  160. threshold=threshold*ThresholdFactor
  161. # Threshold is enlarged because, otherwise, for subsamples at 5' have many false positives
  162. # 1st scenario. Detect only anomaly. Later, we will classiffy it
  163. # Test data= testnormal + testfail1 + testtail2 + testfail3 + testfail4 + testnormal
  164. d=np.vstack((dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4],dataTestNorm[0]))
  165. x_test = create_sequences(d)
  166. x_test_pred = model.predict(x_test)
  167. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  168. # Define ranges for plotting in different colors
  169. testRanges=[]
  170. r=dataTestNorm[0].shape[0]
  171. testRanges.append([0,r])
  172. for i in range(1,NumberOfFailures+1):
  173. rnext=r+dataTestNorm[i].shape[0]
  174. testRanges.append([r,rnext] )
  175. r=rnext
  176. testRanges.append([r, x_test.shape[0]+TIME_STEPS ])
  177. def AtLeastOneTrue(x):
  178. for i in range(NumFeatures):
  179. if x[i]:
  180. return True
  181. return False
  182. anomalies = test_mae_loss > threshold
  183. anomalous_data_indices = []
  184. for i in range(anomalies.shape[0]):
  185. if AtLeastOneTrue(anomalies[i]):
  186. #if anomalies[i][0] or anomalies[i][1] or anomalies[i][2] or anomalies[i][3]:
  187. anomalous_data_indices.append(i)
  188. #print(anomalous_data_indices)
  189. # Let's plot some features
  190. colorline=['violet','lightcoral','cyan','lime','grey']
  191. colordot=['darkviolet','red','blue','green','black']
  192. featuresToPlot=['r1 s1','r1 s2','r1 s3','pa1 apiii']
  193. #featuresToPlot=features
  194. indexesToPlot=[]
  195. for i in featuresToPlot:
  196. indexesToPlot.append(features.index(i))
  197. def plotData2():
  198. NumFeaturesToPlot=len(indexesToPlot)
  199. fig, axes = plt.subplots(
  200. nrows=NumFeaturesToPlot, ncols=1, figsize=(25, 20), dpi=80, facecolor="w", edgecolor="k",sharex=True
  201. )
  202. for i in range(NumFeaturesToPlot):
  203. init=0
  204. end=len(x_train[0])
  205. axes[i].plot(range(init,end),x_train[0][:,0,indexesToPlot[i]],label="normal train")
  206. init=end
  207. end+=testRanges[0][1]
  208. axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],label="normal test")
  209. init=end
  210. end+=(testRanges[1][1]-testRanges[1][0])
  211. for j in range(1,NumberOfFailures+1):
  212. 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])
  213. init=end
  214. end+=(testRanges[j+1][1]-testRanges[j+1][0])
  215. # Shift TIME_STEPS because detection is performed at the end of time serie
  216. trail=np.hstack((x_test[:,0,indexesToPlot[i]], x_test[-1:,1:TIME_STEPS,indexesToPlot[i]].reshape(TIME_STEPS-1)))
  217. axes[i].plot(len(x_train[0])+np.array(anomalous_data_indices)+TIME_STEPS,trail[np.array(anomalous_data_indices)+TIME_STEPS],color='grey',marker='.',linewidth=0,label="abnormal detection" )
  218. init=end-(testRanges[NumberOfFailures+1][1]-testRanges[NumberOfFailures+1][0])
  219. end=init+(testRanges[0][1]-testRanges[0][0])
  220. axes[i].plot(range(init,end),x_test[testRanges[0][0]:testRanges[0][1],0,indexesToPlot[i]],color='orange')
  221. if i==0:
  222. axes[i].legend(bbox_to_anchor=(1, 0.5))
  223. axes[i].set_ylabel(features[indexesToPlot[i]])
  224. axes[i].grid()
  225. plt.show()
  226. def anomalyMetric(testList): # first of list is non failure data
  227. # FP, TP: false/true positive
  228. # TN, FN: true/false negative
  229. # Sensitivity: probab failure detection if data is fail: TP/(TP+FN)
  230. # Specificity: true negative ratio given data is OK: TN/(TN+FP)
  231. x_test = create_sequences(testList[0])
  232. x_test_pred = model.predict(x_test)
  233. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  234. anomalies = test_mae_loss > threshold
  235. count=0
  236. for i in range(anomalies.shape[0]):
  237. if AtLeastOneTrue(anomalies[i]):
  238. count+=1
  239. FP=count
  240. TN=anomalies.shape[0]-count
  241. count=0
  242. TP=np.zeros((NumberOfFailures))
  243. FN=np.zeros((NumberOfFailures))
  244. for i in range(1,len(testList)):
  245. x_test = create_sequences(testList[i])
  246. x_test_pred = model.predict(x_test)
  247. test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
  248. anomalies = test_mae_loss > threshold
  249. count=0
  250. for j in range(anomalies.shape[0]):
  251. if AtLeastOneTrue(anomalies[j]):
  252. count+=1
  253. TP[i-1] = count
  254. FN[i-1] = anomalies.shape[0]-count
  255. Sensitivity=TP.sum()/(TP.sum()+FN.sum())
  256. Specifity=TN/(TN+FP)
  257. print("Sensitivity: ",Sensitivity)
  258. print("Specifity: ",Specifity)
  259. print("FP: ",FP)
  260. return Sensitivity+Specifity
  261. anomalyMetric([dataTestNorm[0],dataTestNorm[1],dataTestNorm[2],dataTestNorm[3],dataTestNorm[4]])
  262. plotData2()

Powered by TurnKey Linux.