a b/code/ml_project.py
1
# -*- coding: utf-8 -*-
2
"""ML_Project.ipynb
3
4
Automatically generated by Colab.
5
6
Original file is located at
7
    https://colab.research.google.com/drive/1N-OfEL_dUBWC58ZTYK4NUEUkakSCj2rS
8
"""
9
10
import pandas as pd
11
12
# Load the data from the CSV file
13
data = pd.read_csv('/content/Dataaa.csv')
14
15
# Display the number of features
16
print("Number of features in the dataset:", data.shape[1])
17
print("Names of the features:", data.columns.tolist())
18
19
# Display the first few lines of the CSV file to understand its content
20
with open('/content/Dataaa.csv', 'r') as file:
21
    for _ in range(5):
22
        print(file.readline())
23
24
import numpy as np
25
import pandas as pd
26
27
# Assuming you have your data loaded into numpy arrays, for example:
28
# X_in is your input data and X_out is your output data
29
# Here is a simple example of how to create these arrays (replace this with your actual data loading code)
30
# X_in = np.random.rand(100, 10)  # Example: 100 samples, 10 features
31
# X_out = np.random.rand(100, 3)  # Example: 100 samples, 3 output targets
32
33
# Convert numpy arrays to pandas DataFrame
34
X_in_df = pd.DataFrame(X_in)
35
X_out_df = pd.DataFrame(X_out)
36
37
# Concatenate both DataFrames along the columns
38
data_df = pd.concat([X_in_df, X_out_df], axis=1)
39
40
# Save the DataFrame to a CSV file
41
data_df.to_csv('/content/corrected_data.csv', index=False)
42
43
import numpy as np
44
import pandas as pd
45
46
# Example data (replace with your actual data arrays)
47
X_in = np.random.rand(100, 10)  # 100 samples, 10 features
48
X_out = np.random.rand(100, 1)  # 100 samples, 1 target
49
50
# Convert to DataFrame
51
df_in = pd.DataFrame(X_in, columns=[f'feature_{i}' for i in range(X_in.shape[1])])
52
df_out = pd.DataFrame(X_out, columns=['target'])
53
54
# Combine input and output data
55
full_df = pd.concat([df_in, df_out], axis=1)
56
57
# Save to CSV
58
full_df.to_csv('/content/corrected_data.csv', index=False)
59
60
import pandas as pd
61
62
# Load the data from the corrected CSV file
63
data = pd.read_csv('/content/corrected_data.csv')
64
65
# Display the first few rows of the dataset and the shape to verify
66
print(data.head())
67
print("Shape of the dataset:", data.shape)
68
print("Column names:", data.columns.tolist())
69
70
##Normalizing and Splitting the data
71
72
from sklearn.model_selection import train_test_split
73
from sklearn.preprocessing import StandardScaler
74
75
# Selecting input features and target
76
X = data.iloc[:, :-1].values  # All columns except the last are features
77
y = data.iloc[:, -1].values  # Last column is the target
78
79
# Normalize the input data
80
scaler = StandardScaler()
81
X_normalized = scaler.fit_transform(X)
82
83
# Split the data into training and testing sets
84
X_train, X_test, y_train, y_test = train_test_split(X_normalized, y, test_size=0.3, random_state=42)
85
86
# Output the shapes of the datasets to verify everything is as expected
87
print("Train data shape:", X_train.shape)
88
print("Test data shape:", X_test.shape)
89
90
##Training the RNN Model
91
92
from tensorflow.keras.models import Sequential
93
from tensorflow.keras.layers import Dense, SimpleRNN
94
95
# Define the RNN model
96
model = Sequential([
97
    SimpleRNN(50, input_shape=(X_train.shape[1], 1)),  # 50 RNN units, considering each feature as a time step
98
    Dense(1)  # Output layer with one neuron for regression output (the target)
99
])
100
101
# Compile the model
102
model.compile(optimizer='adam', loss='mean_squared_error')
103
104
# Reshape input for RNN which expects (batch_size, timesteps, features)
105
X_train_rnn = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
106
X_test_rnn = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
107
108
# Train the model
109
history = model.fit(X_train_rnn, y_train, epochs=100, validation_data=(X_test_rnn, y_test))
110
111
# Optionally, plot the training and validation loss
112
import matplotlib.pyplot as plt
113
114
plt.plot(history.history['loss'], label='train')
115
plt.plot(history.history['val_loss'], label='test')
116
plt.title('Model Loss')
117
plt.ylabel('Loss')
118
plt.xlabel('Epoch')
119
plt.legend()
120
plt.show()
121
122
model.save('/content/my_rnn_model.h5')  # Saves the model for later use
123
124
# Example threshold value - you need to choose what makes sense for your data
125
threshold = 0.5
126
127
# Convert continuous target data to binary classification
128
y_train_class = (y_train > threshold).astype(int)
129
130
# Proceed with the rest of your RNN setup as before
131
132
##Classifying the presence of damage
133
134
from tensorflow.keras.models import Sequential
135
from tensorflow.keras.layers import SimpleRNN, Dense
136
137
# Define the classification model
138
classification_model = Sequential([
139
    SimpleRNN(50, input_shape=(X_train.shape[1], 1)),  # Adjust the input shape and units as necessary
140
    Dense(1, activation='sigmoid')  # Sigmoid activation for binary classification
141
])
142
143
# Compile the classification model
144
classification_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
145
146
# Reshape data for RNN
147
X_train_rnn = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
148
149
# Train the classification model
150
classification_model.fit(X_train_rnn, y_train_class, epochs=100, validation_split=0.2)
151
152
# Save the classification model
153
classification_model.save('/content/classification_model.h5')
154
155
# Assuming your original test labels are in y_test, and they are not binary (0 or 1) yet
156
# Apply the same threshold used for the training data
157
y_test_class = (y_test > threshold).astype(int)
158
159
# Now you can compute the confusion matrix and plot it
160
cm = confusion_matrix(y_test_class, y_pred_class)
161
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
162
disp.plot(cmap=plt.cm.Blues)
163
plt.title('Confusion Matrix')
164
plt.show()
165
166
# And compute the ROC curve
167
fpr, tpr, _ = roc_curve(y_test_class, y_pred_probs.ravel())
168
roc_auc = auc(fpr, tpr)
169
170
# Plot the ROC curve
171
plt.figure()
172
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
173
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
174
plt.xlabel('False Positive Rate')
175
plt.ylabel('True Positive Rate')
176
plt.title('Receiver Operating Characteristic')
177
plt.legend(loc="lower right")
178
plt.show()
179
180
from tensorflow.keras.models import Sequential
181
from tensorflow.keras.layers import LSTM, Dense, Dropout
182
from sklearn.utils.class_weight import compute_class_weight
183
from sklearn.metrics import precision_recall_curve
184
185
# Calculate class weights
186
class_weights = compute_class_weight('balanced', classes=np.unique(y_train_class), y=y_train_class)
187
class_weights_dict = dict(enumerate(class_weights))
188
189
# Build an LSTM model
190
model = Sequential([
191
    LSTM(100, input_shape=(X_train.shape[1], 1), return_sequences=True),
192
    Dropout(0.5),
193
    LSTM(100),
194
    Dropout(0.5),
195
    Dense(1, activation='sigmoid')
196
])
197
198
# Compile the model
199
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
200
201
# Train the model with class weights
202
history = model.fit(X_train_rnn, y_train_class, epochs=100, validation_split=0.2, class_weight=class_weights_dict)
203
204
# Predict probabilities
205
y_pred_probs = model.predict(X_test_rnn)
206
207
# Find the optimal threshold based on precision-recall tradeoff
208
precision, recall, thresholds = precision_recall_curve(y_test_class, y_pred_probs)
209
# Convert to f score
210
fscore = (2 * precision * recall) / (precision + recall)
211
# Locate the index of the largest f score
212
ix = np.argmax(fscore)
213
optimal_threshold = thresholds[ix]
214
215
# Use the optimal threshold to convert probabilities to binary predictions
216
y_pred_class = (y_pred_probs > optimal_threshold).astype(int)
217
218
# Recompute the confusion matrix and ROC curve using the new threshold
219
220
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc
221
import matplotlib.pyplot as plt
222
223
# Use the optimal threshold to convert probabilities to binary predictions
224
y_pred_class_optimal = (y_pred_probs > optimal_threshold).astype(int)
225
226
# Compute the confusion matrix using the optimal threshold
227
cm_optimal = confusion_matrix(y_test_class, y_pred_class_optimal)
228
229
# Display the confusion matrix
230
disp = ConfusionMatrixDisplay(confusion_matrix=cm_optimal)
231
disp.plot(cmap=plt.cm.Blues)
232
plt.title('Confusion Matrix with Optimal Threshold')
233
plt.show()
234
235
# Compute ROC curve and AUC
236
fpr, tpr, _ = roc_curve(y_test_class, y_pred_probs)
237
roc_auc = auc(fpr, tpr)
238
239
# Plot ROC curve
240
plt.figure()
241
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
242
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
243
plt.xlabel('False Positive Rate')
244
plt.ylabel('True Positive Rate')
245
plt.title('Receiver Operating Characteristic with Optimal Threshold')
246
plt.legend(loc="lower right")
247
plt.show()
248
249
# Make sure the 'y_test_class' and 'y_train_class' variables are set correctly before this step.
250
# For the sake of example, let's assume 'y_test' is the variable holding the original test labels.
251
252
# Verify and correct labels if necessary
253
# 'damage' is 1, 'no damage' is 0
254
y_test_class = np.where(y_test == 'damage', 1, 0)
255
256
# Now, use your model to predict probabilities on the test set
257
# Assuming 'X_test_rnn' is already defined and shaped correctly
258
y_pred_probs = classification_model.predict(X_test_rnn)
259
260
# Choose a decision threshold (if you've found an optimal one, use that, otherwise use 0.5)
261
threshold = 0.5  # or optimal_threshold if you have one
262
263
# Convert predicted probabilities into binary class predictions
264
y_pred_class = (y_pred_probs > threshold).astype(int)
265
266
# Compute the confusion matrix
267
cm = confusion_matrix(y_test_class, y_pred_class)
268
269
# Plot the confusion matrix
270
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
271
disp.plot(cmap=plt.cm.Blues)
272
plt.title('Confusion Matrix')
273
plt.show()
274
275
# Calculate the ROC curve and AUC
276
fpr, tpr, _ = roc_curve(y_test_class, y_pred_probs)
277
roc_auc = auc(fpr, tpr)
278
279
# Plot the ROC curve
280
plt.figure()
281
plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
282
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
283
plt.xlabel('False Positive Rate')
284
plt.ylabel('True Positive Rate')
285
plt.title('Receiver Operating Characteristic')
286
plt.legend(loc='lower right')
287
plt.show()
288
289
# Reshape data from 2D to 3D (samples, timesteps, features)
290
X_train_rnn = X_train.reshape((X_train.shape[0], 1, X_train.shape[1]))
291
292
# Define the LSTM model for binary classification
293
lstm_model = Sequential([
294
    LSTM(50, input_shape=(X_train_rnn.shape[1], X_train_rnn.shape[2])),  # Correct input_shape
295
    Dense(1, activation='sigmoid')
296
])
297
298
# Compile the LSTM model
299
lstm_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
300
301
# Train the LSTM model
302
history = lstm_model.fit(X_train_rnn, y_train_class, epochs=100, validation_split=0.2)
303
304
# ... (Continue with the rest of the code as before)
305
306
# Assuming your data is correctly reshaped to 3D for LSTM and 'y_train_class' holds the binary labels
307
308
# Continue training the LSTM model
309
history = lstm_model.fit(
310
    X_train_rnn,
311
    y_train_class,
312
    epochs=100,
313
    validation_split=0.2
314
)
315
316
# Assuming 'X_test' and 'y_test' are your test data and labels, respectively
317
# Reshape the test data to match the input shape of the model
318
X_test_rnn = X_test.reshape((X_test.shape[0], 1, X_test.shape[1]))
319
320
# Predict class probabilities on the test set
321
y_pred_probs = lstm_model.predict(X_test_rnn)
322
323
# Choose a decision threshold
324
threshold = 0.5  # Adjust based on your optimal threshold
325
y_pred_class = (y_pred_probs > threshold).astype(int)
326
327
# Compute the confusion matrix
328
cm = confusion_matrix(y_test_class, y_pred_class)
329
330
# Display the confusion matrix
331
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
332
disp.plot(cmap=plt.cm.Blues)
333
plt.title('Confusion Matrix - LSTM Model')
334
plt.show()
335
336
# Compute ROC curve and AUC
337
fpr, tpr, _ = roc_curve(y_test_class, y_pred_probs)
338
roc_auc = auc(fpr, tpr)
339
340
# Plot ROC curve
341
plt.figure()
342
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
343
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
344
plt.xlabel('False Positive Rate')
345
plt.ylabel('True Positive Rate')
346
plt.title('ROC Curve - LSTM Model')
347
plt.legend(loc="lower right")
348
plt.show()
349
350
# Check the range of predicted probabilities
351
print("Predicted probabilities:", y_pred_probs)
352
353
# Check if there are both classes present in the test labels
354
print("Unique labels in y_test_class:", np.unique(y_test_class))
355
356
# Check unique values in the labels array
357
unique_classes = np.unique(y)
358
print("Unique classes in y:", unique_classes)
359
360
# Define a threshold to convert continuous values to binary classification
361
threshold = 0.5  # This is just an example, adjust this based on your domain knowledge
362
y_class = (y > threshold).astype(int)
363
364
# Now check the distribution of the new binary labels
365
print("Distribution of binary labels:", np.bincount(y_class))
366
367
# Continue with the train-test split with the new binary labels
368
X_train, X_test, y_train_class, y_test_class = train_test_split(
369
    X, y_class,
370
    test_size=0.2,
371
    stratify=y_class,
372
    random_state=42
373
)
374
375
from sklearn.linear_model import LogisticRegression
376
from sklearn.metrics import confusion_matrix, roc_curve, auc, ConfusionMatrixDisplay
377
import matplotlib.pyplot as plt
378
379
# Perform the stratified train-test split with the new binary labels
380
X_train, X_test, y_train_class, y_test_class = train_test_split(
381
    X, y_class,
382
    test_size=0.2,
383
    stratify=y_class,
384
    random_state=42
385
)
386
387
# Train the logistic regression model
388
logistic_model = LogisticRegression()
389
logistic_model.fit(X_train, y_train_class)
390
391
# Predict class probabilities on the test set
392
y_pred_probs_logistic = logistic_model.predict_proba(X_test)[:, 1]
393
394
# Predict class labels for the test set based on the default threshold of 0.5
395
y_pred_class_logistic = logistic_model.predict(X_test)
396
397
# Compute the confusion matrix
398
cm_logistic = confusion_matrix(y_test_class, y_pred_class_logistic)
399
400
# Display the confusion matrix
401
disp = ConfusionMatrixDisplay(confusion_matrix=cm_logistic)
402
disp.plot(cmap=plt.cm.Blues)
403
plt.title('Confusion Matrix - Logistic Regression Model')
404
plt.show()
405
406
# Compute ROC curve and AUC
407
fpr_logistic, tpr_logistic, _ = roc_curve(y_test_class, y_pred_probs_logistic)
408
roc_auc_logistic = auc(fpr_logistic, tpr_logistic)
409
410
# Plot the ROC curve
411
plt.figure()
412
plt.plot(fpr_logistic, tpr_logistic, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_logistic)
413
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
414
plt.xlabel('False Positive Rate')
415
plt.ylabel('True Positive Rate')
416
plt.title('ROC Curve - Logistic Regression Model')
417
plt.legend(loc="lower right")
418
plt.show()
419
420
# Reshape X_test_rnn to match the expected input shape of the model (10 time steps, 1 feature per step)
421
X_test_rnn_reshaped = X_test_rnn.reshape((X_test_rnn.shape[0], 10, 1))
422
423
# Now make predictions with the reshaped data
424
y_pred_probs_rnn = rnn_model.predict(X_test_rnn_reshaped)
425
426
# Continue with the rest of the code for evaluation
427
428
print("Number of samples in test set:", y_test_class.shape[0])
429
print("Number of predictions made:", y_pred_probs_rnn.shape[0])
430
431
432
433
434
435
##Using LSTM to better predict
436
437
from tensorflow.keras.models import Sequential
438
from tensorflow.keras.layers import LSTM, Dense
439
440
# Define the LSTM model for binary classification
441
lstm_classification_model = Sequential([
442
    LSTM(2, input_shape=(X_train.shape[1], 1)),  # 50 LSTM units
443
    Dense(1, activation='sigmoid')  # Sigmoid activation for binary classification
444
])
445
446
# Compile the LSTM model
447
lstm_classification_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
448
449
# Train the LSTM model
450
history = lstm_classification_model.fit(
451
    X_train_rnn, y_train_class,
452
    epochs=100,
453
    validation_split=0.2
454
)
455
456
# Save the LSTM classification model
457
lstm_classification_model.save('/content/lstm_classification_model.h5')
458
459
#Model Evaluation
460
461
# Evaluate the model's performance
462
test_loss, test_accuracy = lstm_classification_model.evaluate(X_test_rnn, y_test_binary)
463
464
# Print the evaluation results
465
print(f"Test Loss: {test_loss}")
466
print(f"Test Accuracy: {test_accuracy}")
467
468
#Regularizing to make LSTM better
469
470
from sklearn.utils.class_weight import compute_class_weight
471
472
# Calculate class weights for unbalanced datasets
473
class_weights = compute_class_weight(
474
    class_weight='balanced',
475
    classes=np.unique(y_train_class),
476
    y=y_train_class
477
)
478
479
# Create a dictionary mapping class labels to weights
480
weight_for_class_1 = class_weights[1]
481
class_weight_dict = {0: class_weights[0], 1: class_weights[1]}
482
483
# Train the model with class weight to handle imbalance
484
history = lstm_classification_model.fit(
485
    X_train_rnn, y_train_class,
486
    epochs=100,
487
    validation_split=0.2,
488
    class_weight=class_weight_dict  # Use the computed class weights
489
)
490
491
# Plot the training history
492
plt.figure(figsize=(14, 5))
493
494
# Plot training & validation accuracy values
495
plt.subplot(1, 2, 1)
496
plt.plot(history.history['accuracy'])
497
plt.plot(history.history['val_accuracy'])
498
plt.title('Model accuracy')
499
plt.xlabel('Epoch')
500
plt.ylabel('Accuracy')
501
plt.legend(['Train', 'Test'], loc='upper left')
502
503
# Plot training & validation loss values
504
plt.subplot(1, 2, 2)
505
plt.plot(history.history['loss'])
506
plt.plot(history.history['val_loss'])
507
plt.title('Model loss')
508
plt.xlabel('Epoch')
509
plt.ylabel('Loss')
510
plt.legend(['Train', 'Test'], loc='upper left')
511
512
plt.show()
513
514
from tensorflow.keras.models import Sequential
515
from tensorflow.keras.layers import LSTM, Dense, Dropout
516
from sklearn.utils.class_weight import compute_class_weight
517
518
# Calculate class weights for unbalanced datasets
519
classes = np.unique(y_train_class)
520
class_weights = compute_class_weight(class_weight='balanced', classes=classes, y=y_train_class)
521
class_weights_dict = dict(zip(classes, class_weights))
522
523
# Define the LSTM model with dropout for regularization
524
model = Sequential([
525
    LSTM(30, input_shape=(X_train.shape[1], 1), dropout=0.2, recurrent_dropout=0.2),
526
    Dropout(0.5),
527
    Dense(1, activation='sigmoid')
528
])
529
530
# Compile the model with a possibly smaller learning rate and class weight
531
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
532
533
# Train the model with class weights to handle imbalance
534
history = model.fit(
535
    X_train_rnn, y_train_class,
536
    epochs=50,
537
    validation_split=0.2,
538
    class_weight=class_weights_dict,
539
    batch_size=32  # Consider trying different batch sizes
540
)
541
542
# Evaluate the model to see if the performance has improved
543
test_loss, test_accuracy = model.evaluate(X_test_rnn, y_test_binary)
544
print(f"Test Loss: {test_loss}")
545
print(f"Test Accuracy: {test_accuracy}")
546
547
# Predict classes using the trained model
548
y_pred_class = (model.predict(X_test_rnn) > 0.5).astype(int)
549
550
# Generate the new confusion matrix
551
cm = confusion_matrix(y_test_binary, y_pred_class)
552
553
# Plot the confusion matrix
554
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
555
disp.plot(cmap=plt.cm.Blues)
556
plt.title('Confusion Matrix')
557
plt.show()
558
559
from sklearn.model_selection import TimeSeriesSplit
560
from tensorflow.keras.models import Sequential
561
from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
562
from sklearn.metrics import confusion_matrix, roc_curve, auc
563
564
# Define the number of splits
565
n_splits = 5
566
tscv = TimeSeriesSplit(n_splits=n_splits)
567
568
# To store metrics for each fold
569
confusion_matrices = []
570
roc_auc_scores = []
571
572
for train_index, test_index in tscv.split(X_normalized):
573
    X_train_cv, X_test_cv = X_normalized[train_index], X_normalized[test_index]
574
    y_train_cv, y_test_cv = y_binary[train_index], y_binary[test_index]
575
576
    # Reshape the data for LSTM network
577
    X_train_cv_rnn = X_train_cv.reshape((X_train_cv.shape[0], X_train_cv.shape[1], 1))
578
    X_test_cv_rnn = X_test_cv.reshape((X_test_cv.shape[0], X_test_cv.shape[1], 1))
579
580
    # Define the model (as before)
581
    model = Sequential([
582
        Bidirectional(LSTM(50, input_shape=(X_train_cv_rnn.shape[1], 1))),
583
        Dropout(0.5),
584
        Dense(1, activation='sigmoid')
585
    ])
586
587
    # Compile the model (as before)
588
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
589
590
    # Fit the model
591
    model.fit(X_train_cv_rnn, y_train_cv, epochs=100, batch_size=32, verbose=0)  # Set verbose to 0 to suppress output
592
593
    # Predict probabilities
594
    y_pred_probs = model.predict(X_test_cv_rnn).ravel()
595
596
    # Binarize predictions based on threshold
597
    threshold = 0.5  # This threshold can be adjusted
598
    y_pred_class = (y_pred_probs > threshold).astype(int)
599
600
    # Calculate metrics for this fold
601
    cm = confusion_matrix(y_test_cv, y_pred_class)
602
    confusion_matrices.append(cm)
603
604
    fpr, tpr, thresholds = roc_curve(y_test_cv, y_pred_probs)
605
    roc_auc = auc(fpr, tpr)
606
    roc_auc_scores.append(roc_auc)
607
608
# Now, you can calculate the average of the metrics across all folds
609
# Average Confusion Matrix
610
average_cm = np.mean(confusion_matrices, axis=0)
611
print("Average Confusion Matrix:\n", average_cm)
612
613
# Average ROC AUC Score
614
average_roc_auc = np.mean(roc_auc_scores)
615
print("Average ROC AUC Score:", average_roc_auc)
616
617
import numpy as np
618
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
619
import matplotlib.pyplot as plt
620
621
# Assume 'model' is your trained Keras model
622
# Predict probabilities for the test set
623
y_pred_probs = model.predict(X_test_rnn)
624
625
# Function to apply threshold to probabilities to create binary predictions
626
def apply_threshold(probs, threshold):
627
    return (probs > threshold).astype(int)
628
629
# Choose a range of thresholds to try
630
thresholds = np.linspace(0, 1, 101)
631
632
# Plot confusion matrices for various thresholds
633
fig, axes = plt.subplots(nrows=10, ncols=10, figsize=(20, 20))  # Adjust the subplot grid as needed
634
axes = axes.flatten()  # Flatten to 1D array for easy iteration
635
636
for ax, threshold in zip(axes, thresholds):
637
    # Get binary predictions using the current threshold
638
    y_pred_class = apply_threshold(y_pred_probs, threshold)
639
640
    # Compute the confusion matrix for this threshold
641
    cm = confusion_matrix(y_test_binary, y_pred_class)
642
643
    # Plot the confusion matrix
644
    ConfusionMatrixDisplay(confusion_matrix=cm).plot(cmap=plt.cm.Blues, ax=ax)
645
    ax.title.set_text(f'Thr {threshold:.2f}')
646
647
plt.tight_layout()  # Adjust spacing
648
plt.show()
649
650
from sklearn.metrics import roc_curve, auc
651
import matplotlib.pyplot as plt
652
653
# Assume 'model' is your trained Keras model and you have a test set 'X_test_rnn'
654
# Predict probabilities for the positive class (damage)
655
y_pred_probs = model.predict(X_test_rnn).ravel()
656
657
# Compute ROC curve and ROC area for each class
658
fpr, tpr, thresholds = roc_curve(y_test_binary, y_pred_probs)
659
roc_auc = auc(fpr, tpr)
660
661
# Plot the ROC curve
662
plt.figure()
663
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
664
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
665
plt.xlim([0.0, 1.0])
666
plt.ylim([0.0, 1.05])
667
plt.xlabel('False Positive Rate')
668
plt.ylabel('True Positive Rate')
669
plt.title('Receiver Operating Characteristic')
670
plt.legend(loc="lower right")
671
plt.show()
672
673
##using a bidirectional LSTM model
674
from tensorflow.keras.models import Sequential
675
from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
676
677
# Define the bidirectional LSTM model
678
bidirectional_lstm_model = Sequential([
679
    Bidirectional(LSTM(50, return_sequences=True), input_shape=(X_train.shape[1], 1)),
680
    Dropout(0.5),
681
    Bidirectional(LSTM(50)),
682
    Dropout(0.5),
683
    Dense(1, activation='sigmoid')
684
])
685
686
# Compile the model
687
bidirectional_lstm_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
688
689
# Train the model
690
history = bidirectional_lstm_model.fit(
691
    X_train_rnn, y_train_class,
692
    epochs=100,
693
    validation_split=0.2
694
)
695
696
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc
697
import matplotlib.pyplot as plt
698
699
# Make predictions on the test data
700
y_pred_probs = bidirectional_lstm_model.predict(X_test_rnn)
701
y_pred_class = (y_pred_probs > 0.5).astype(int)
702
703
# Confusion Matrix
704
cm = confusion_matrix(y_test_binary, y_pred_class)
705
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
706
disp.plot(cmap=plt.cm.Blues)
707
plt.title('Confusion Matrix')
708
plt.show()
709
710
# ROC Curve
711
fpr, tpr, thresholds = roc_curve(y_test_binary, y_pred_probs)
712
roc_auc = auc(fpr, tpr)
713
714
plt.figure()
715
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
716
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
717
plt.xlim([0.0, 1.0])
718
plt.ylim([0.0, 1.05])
719
plt.xlabel('False Positive Rate')
720
plt.ylabel('True Positive Rate')
721
plt.title('Receiver Operating Characteristic')
722
plt.legend(loc="lower right")
723
plt.show()
724
725
from sklearn.model_selection import TimeSeriesSplit
726
from tensorflow.keras.models import Sequential
727
from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
728
from sklearn.metrics import confusion_matrix, roc_curve, auc
729
730
# Define the number of splits
731
n_splits = 5
732
tscv = TimeSeriesSplit(n_splits=n_splits)
733
734
# To store metrics for each fold
735
confusion_matrices = []
736
roc_auc_scores = []
737
738
for train_index, test_index in tscv.split(X_normalized):
739
    X_train_cv, X_test_cv = X_normalized[train_index], X_normalized[test_index]
740
    y_train_cv, y_test_cv = y_binary[train_index], y_binary[test_index]
741
742
    # Reshape the data for LSTM network
743
    X_train_cv_rnn = X_train_cv.reshape((X_train_cv.shape[0], X_train_cv.shape[1], 1))
744
    X_test_cv_rnn = X_test_cv.reshape((X_test_cv.shape[0], X_test_cv.shape[1], 1))
745
746
    # Define the model (as before)
747
    model = Sequential([
748
        Bidirectional(LSTM(50, input_shape=(X_train_cv_rnn.shape[1], 1))),
749
        Dropout(0.5),
750
        Dense(1, activation='sigmoid')
751
    ])
752
753
    # Compile the model (as before)
754
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
755
756
    # Fit the model
757
    model.fit(X_train_cv_rnn, y_train_cv, epochs=100, batch_size=32, verbose=0)  # Set verbose to 0 to suppress output
758
759
    # Predict probabilities
760
    y_pred_probs = model.predict(X_test_cv_rnn).ravel()
761
762
    # Binarize predictions based on threshold
763
    threshold = 0.5  # This threshold can be adjusted
764
    y_pred_class = (y_pred_probs > threshold).astype(int)
765
766
    # Calculate metrics for this fold
767
    cm = confusion_matrix(y_test_cv, y_pred_class)
768
    confusion_matrices.append(cm)
769
770
    fpr, tpr, thresholds = roc_curve(y_test_cv, y_pred_probs)
771
    roc_auc = auc(fpr, tpr)
772
    roc_auc_scores.append(roc_auc)
773
774
# Now, you can calculate the average of the metrics across all folds
775
# Average Confusion Matrix
776
average_cm = np.mean(confusion_matrices, axis=0)
777
print("Average Confusion Matrix:\n", average_cm)
778
779
# Average ROC AUC Score
780
average_roc_auc = np.mean(roc_auc_scores)
781
print("Average ROC AUC Score:", average_roc_auc)
782
783
784
785
786
787
788