Update cnn_SaveInPainting.py
Browse files- cnn_SaveInPainting.py +255 -281
cnn_SaveInPainting.py
CHANGED
@@ -1,281 +1,255 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""
|
3 |
-
Created on Sat May 18 16:15:32 2024
|
4 |
-
@author: litav
|
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 |
-
for
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
#
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
# Function to
|
102 |
-
def
|
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 |
-
plt.
|
236 |
-
plt.show()
|
237 |
-
|
238 |
-
# Plot
|
239 |
-
plt.figure(figsize=(12, 4))
|
240 |
-
plt.subplot(1, 2, 1)
|
241 |
-
plt.plot(
|
242 |
-
plt.
|
243 |
-
plt.
|
244 |
-
plt.ylabel('Accuracy')
|
245 |
-
|
246 |
-
plt.
|
247 |
-
plt.
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
plt.
|
253 |
-
plt
|
254 |
-
|
255 |
-
|
256 |
-
plt.xlabel('Epoch')
|
257 |
-
plt.legend(['Train', 'Validation'], loc='upper left')
|
258 |
-
plt.xticks(np.arange(0, len(history.history['loss']), step=1), np.arange(1, len(history.history['loss']) + 1, step=1))
|
259 |
-
|
260 |
-
|
261 |
-
plt.tight_layout()
|
262 |
-
plt.show()
|
263 |
-
|
264 |
-
# Plot validation accuracy and loss per fold
|
265 |
-
plt.figure(figsize=(12, 4))
|
266 |
-
plt.subplot(1, 2, 1)
|
267 |
-
plt.plot(range(1, kf.get_n_splits() + 1), accuracy_per_fold, marker='o')
|
268 |
-
plt.title('Validation Accuracy per Fold')
|
269 |
-
plt.xlabel('Fold')
|
270 |
-
plt.ylabel('Accuracy')
|
271 |
-
|
272 |
-
plt.subplot(1, 2, 2)
|
273 |
-
plt.plot(range(1, kf.get_n_splits() + 1), loss_per_fold, marker='o')
|
274 |
-
plt.title('Validation Loss per Fold')
|
275 |
-
plt.xlabel('Fold')
|
276 |
-
plt.ylabel('Loss')
|
277 |
-
|
278 |
-
plt.tight_layout()
|
279 |
-
plt
|
280 |
-
|
281 |
-
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
Created on Sat May 18 16:15:32 2024
|
4 |
+
@author: litav
|
5 |
+
"""
|
6 |
+
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import tensorflow as tf
|
10 |
+
import random
|
11 |
+
import os
|
12 |
+
import pandas as pd
|
13 |
+
import cv2
|
14 |
+
import matplotlib.pyplot as plt
|
15 |
+
from sklearn.model_selection import KFold
|
16 |
+
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
|
17 |
+
from tensorflow.keras.optimizers import Adam
|
18 |
+
from tensorflow.keras.models import Sequential
|
19 |
+
from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay
|
20 |
+
from tensorflow.keras.layers import Dropout
|
21 |
+
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
|
22 |
+
from sklearn.metrics import precision_score, recall_score, f1_score, classification_report
|
23 |
+
|
24 |
+
|
25 |
+
# Suppress iCCP warning
|
26 |
+
import warnings
|
27 |
+
warnings.filterwarnings("ignore", category=UserWarning, message=".*iCCP:.*")
|
28 |
+
|
29 |
+
# Define data paths
|
30 |
+
train_real_folder = 'datasets/training_set/real/'
|
31 |
+
train_fake_folder = 'datasets/training_set/fake/'
|
32 |
+
test_real_folder = 'datasets/test_set/real/'
|
33 |
+
test_fake_folder = 'datasets/test_set/fake/'
|
34 |
+
|
35 |
+
# Load train image paths and labels
|
36 |
+
train_image_paths = []
|
37 |
+
train_labels = []
|
38 |
+
|
39 |
+
# Load train_real image paths and labels
|
40 |
+
for filename in os.listdir(train_real_folder):
|
41 |
+
image_path = os.path.join(train_real_folder, filename)
|
42 |
+
label = 0 # Real images have label 0
|
43 |
+
train_image_paths.append(image_path)
|
44 |
+
train_labels.append(label)
|
45 |
+
|
46 |
+
# Load train_fake image paths and labels
|
47 |
+
for filename in os.listdir(train_fake_folder):
|
48 |
+
image_path = os.path.join(train_fake_folder, filename)
|
49 |
+
label = 1 # Fake images have label 1
|
50 |
+
train_image_paths.append(image_path)
|
51 |
+
train_labels.append(label)
|
52 |
+
|
53 |
+
# Load test image paths and labels
|
54 |
+
test_image_paths = []
|
55 |
+
test_labels = []
|
56 |
+
|
57 |
+
# Load test_real image paths and labels
|
58 |
+
for filename in os.listdir(test_real_folder):
|
59 |
+
image_path = os.path.join(test_real_folder, filename)
|
60 |
+
label = 0 # Assuming test real images are all real (label 0)
|
61 |
+
test_image_paths.append(image_path)
|
62 |
+
test_labels.append(label)
|
63 |
+
|
64 |
+
# Load test_fake image paths and labels
|
65 |
+
for filename in os.listdir(test_fake_folder):
|
66 |
+
image_path = os.path.join(test_fake_folder, filename)
|
67 |
+
label = 1 # Assuming test fake images are all fake (label 1)
|
68 |
+
test_image_paths.append(image_path)
|
69 |
+
test_labels.append(label)
|
70 |
+
|
71 |
+
# Create DataFrames
|
72 |
+
train_dataset = pd.DataFrame({'image_path': train_image_paths, 'label': train_labels})
|
73 |
+
test_dataset = pd.DataFrame({'image_path': test_image_paths, 'label': test_labels})
|
74 |
+
|
75 |
+
# Function to preprocess images
|
76 |
+
def preprocess_image(image_path):
|
77 |
+
"""Loads, resizes, and normalizes an image."""
|
78 |
+
image = cv2.imread(image_path)
|
79 |
+
resized_image = cv2.resize(image, (128, 128)) # Target size defined here
|
80 |
+
normalized_image = resized_image.astype(np.float32) / 255.0
|
81 |
+
return normalized_image
|
82 |
+
|
83 |
+
# Preprocess all images and convert labels to numpy arrays
|
84 |
+
X = np.array([preprocess_image(path) for path in train_image_paths])
|
85 |
+
Y = np.array(train_labels)
|
86 |
+
|
87 |
+
# Define discriminator network
|
88 |
+
def build_discriminator(input_shape, dropout_rate=0.5):
|
89 |
+
model = Sequential()
|
90 |
+
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
|
91 |
+
model.add(MaxPooling2D((2, 2)))
|
92 |
+
model.add(Conv2D(64, (3, 3), activation='relu'))
|
93 |
+
model.add(MaxPooling2D((2, 2)))
|
94 |
+
model.add(Conv2D(64, (3, 3), activation='relu'))
|
95 |
+
model.add(Flatten())
|
96 |
+
model.add(Dense(64, activation='relu'))
|
97 |
+
model.add(Dropout(dropout_rate)) # Adding dropout layer
|
98 |
+
model.add(Dense(1, activation='sigmoid'))
|
99 |
+
return model
|
100 |
+
|
101 |
+
# Function to check if previous weights exist
|
102 |
+
def load_previous_weights(model, fold_number):
|
103 |
+
weights_file = f'model_weights/model_fold_{fold_number}.weights.h5'
|
104 |
+
if os.path.exists(weights_file):
|
105 |
+
model.load_weights(weights_file)
|
106 |
+
print(f"Loaded weights from {weights_file}")
|
107 |
+
else:
|
108 |
+
print("No previous weights found.")
|
109 |
+
|
110 |
+
# Function to save weights if current accuracy is higher
|
111 |
+
def save_updated_weights(model, fold_number, val_accuracy, best_accuracy):
|
112 |
+
weights_file = f'model_weights/model_fold_{fold_number}.weights.h5'
|
113 |
+
if val_accuracy > best_accuracy:
|
114 |
+
model.save_weights(weights_file)
|
115 |
+
print(f"Saved updated weights to {weights_file} with val_accuracy: {val_accuracy:.4f}")
|
116 |
+
return val_accuracy
|
117 |
+
else:
|
118 |
+
print(f"Did not save weights for fold {fold_number} as val_accuracy {val_accuracy:.4f} is not better than {best_accuracy:.4f}")
|
119 |
+
return best_accuracy
|
120 |
+
|
121 |
+
# Set parameters for cross-validation
|
122 |
+
kf = KFold(n_splits=4, shuffle=True, random_state=42)
|
123 |
+
batch_size = 32
|
124 |
+
epochs = 15
|
125 |
+
|
126 |
+
# Lists to store accuracy and loss for each fold
|
127 |
+
accuracy_per_fold = []
|
128 |
+
loss_per_fold = []
|
129 |
+
# Store the best accuracies for each fold
|
130 |
+
best_accuracies = [0] * kf.get_n_splits()
|
131 |
+
|
132 |
+
|
133 |
+
# Perform K-Fold Cross-Validation
|
134 |
+
for fold_number, (train_index, val_index) in enumerate(kf.split(X), 1):
|
135 |
+
X_train, X_val = X[train_index], X[val_index]
|
136 |
+
Y_train, Y_val = Y[train_index], Y[val_index]
|
137 |
+
|
138 |
+
# Create and compile model
|
139 |
+
input_dim = X_train.shape[1:] # Dimensionality of the input images
|
140 |
+
model = build_discriminator(input_dim)
|
141 |
+
model.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5), metrics=['accuracy'])
|
142 |
+
|
143 |
+
# Load previous weights if they exist
|
144 |
+
load_previous_weights(model, fold_number)
|
145 |
+
|
146 |
+
# Define Early Stopping callback
|
147 |
+
early_stopping = EarlyStopping(monitor='val_accuracy', patience=5, restore_best_weights=True)
|
148 |
+
|
149 |
+
# Define ModelCheckpoint callback to save the best weights
|
150 |
+
checkpoint = ModelCheckpoint(filepath=f'best_model_weights/model_fold_{fold_number}.best.weights.h5.keras', monitor='val_accuracy', save_best_only=True, mode='max')
|
151 |
+
|
152 |
+
# Train the model with the callbacks
|
153 |
+
history = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=2,
|
154 |
+
validation_data=(X_val, Y_val), callbacks=[early_stopping, checkpoint])
|
155 |
+
|
156 |
+
# Store the accuracy and loss for this folds
|
157 |
+
average_val_accuracy = np.mean(history.history['val_accuracy'])
|
158 |
+
accuracy_per_fold.append(average_val_accuracy)
|
159 |
+
average_val_loss = np.mean(history.history['val_loss'])
|
160 |
+
loss_per_fold.append(average_val_loss)
|
161 |
+
|
162 |
+
# Save updated weights if accuracy is high
|
163 |
+
best_accuracies[fold_number - 1] = save_updated_weights(model, fold_number, average_val_accuracy, best_accuracies[fold_number - 1])
|
164 |
+
|
165 |
+
|
166 |
+
# Print fold accuracy
|
167 |
+
print(f'Fold {fold_number} average accuracy: {average_val_accuracy*100:.2f}%')
|
168 |
+
|
169 |
+
# Print average accuracy across all folds
|
170 |
+
print(f'Average accuracy across all folds: {np.mean(accuracy_per_fold)*100:.2f}%')
|
171 |
+
|
172 |
+
# Load the model weights of the best model
|
173 |
+
best_model_index = np.argmax(accuracy_per_fold)
|
174 |
+
best_model_path = f'best_model_weights/model_fold_{best_model_index + 1}.best.weights.h5.keras'
|
175 |
+
model.load_weights(best_model_path)
|
176 |
+
|
177 |
+
# Evaluate the preprocessed test images using the best model
|
178 |
+
test_loss, test_accuracy = model.evaluate(np.array([preprocess_image(path) for path in test_image_paths]), np.array(test_labels))
|
179 |
+
print(f"\nTest Loss: {test_loss}, Test Accuracy: {test_accuracy}")
|
180 |
+
|
181 |
+
# Predict labels for the test set using the best model
|
182 |
+
predictions = model.predict(np.array([preprocess_image(path) for path in test_image_paths]))
|
183 |
+
predicted_labels = (predictions > 0.5).astype(int).flatten()
|
184 |
+
|
185 |
+
# Summarize the classification results
|
186 |
+
true_real_correct = np.sum((np.array(test_labels) == 0) & (predicted_labels == 0))
|
187 |
+
true_real_incorrect = np.sum((np.array(test_labels) == 0) & (predicted_labels == 1))
|
188 |
+
true_fake_correct = np.sum((np.array(test_labels) == 1) & (predicted_labels == 1))
|
189 |
+
true_fake_incorrect = np.sum((np.array(test_labels) == 1) & (predicted_labels == 0))
|
190 |
+
|
191 |
+
print("\nClassification Summary:")
|
192 |
+
print(f"Real images correctly classified: {true_real_correct}")
|
193 |
+
print(f"Real images incorrectly classified: {true_real_incorrect}")
|
194 |
+
print(f"Fake images correctly classified: {true_fake_correct}")
|
195 |
+
print(f"Fake images incorrectly classified: {true_fake_incorrect}")
|
196 |
+
|
197 |
+
|
198 |
+
# Print detailed classification report
|
199 |
+
print("\nClassification Report:")
|
200 |
+
print(classification_report(test_labels, predicted_labels, target_names=['Real', 'Fake']))
|
201 |
+
|
202 |
+
print(model.summary())
|
203 |
+
|
204 |
+
|
205 |
+
# Plot confusion matrix
|
206 |
+
cm = confusion_matrix(test_labels, predicted_labels)
|
207 |
+
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['Real', 'Fake'])
|
208 |
+
disp.plot(cmap=plt.cm.Blues)
|
209 |
+
plt.title("Confusion Matrix")
|
210 |
+
plt.show()
|
211 |
+
|
212 |
+
# Plot training & validation accuracy values
|
213 |
+
plt.figure(figsize=(12, 4))
|
214 |
+
plt.subplot(1, 2, 1)
|
215 |
+
plt.plot(history.history['accuracy'])
|
216 |
+
plt.plot(history.history['val_accuracy'])
|
217 |
+
plt.title('Model accuracy')
|
218 |
+
plt.ylabel('Accuracy')
|
219 |
+
plt.xlabel('Epoch')
|
220 |
+
plt.legend(['Train', 'Validation'], loc='upper left')
|
221 |
+
plt.xticks(np.arange(0, len(history.history['accuracy']), step=1), np.arange(1, len(history.history['accuracy']) + 1, step=1))
|
222 |
+
|
223 |
+
|
224 |
+
# Plot training & validation loss values
|
225 |
+
plt.subplot(1, 2, 2)
|
226 |
+
plt.plot(history.history['loss'])
|
227 |
+
plt.plot(history.history['val_loss'])
|
228 |
+
plt.title('Model loss')
|
229 |
+
plt.ylabel('Loss')
|
230 |
+
plt.xlabel('Epoch')
|
231 |
+
plt.legend(['Train', 'Validation'], loc='upper left')
|
232 |
+
plt.xticks(np.arange(0, len(history.history['loss']), step=1), np.arange(1, len(history.history['loss']) + 1, step=1))
|
233 |
+
|
234 |
+
|
235 |
+
plt.tight_layout()
|
236 |
+
plt.show()
|
237 |
+
|
238 |
+
# Plot validation accuracy and loss per fold
|
239 |
+
plt.figure(figsize=(12, 4))
|
240 |
+
plt.subplot(1, 2, 1)
|
241 |
+
plt.plot(range(1, kf.get_n_splits() + 1), accuracy_per_fold, marker='o')
|
242 |
+
plt.title('Validation Accuracy per Fold')
|
243 |
+
plt.xlabel('Fold')
|
244 |
+
plt.ylabel('Accuracy')
|
245 |
+
|
246 |
+
plt.subplot(1, 2, 2)
|
247 |
+
plt.plot(range(1, kf.get_n_splits() + 1), loss_per_fold, marker='o')
|
248 |
+
plt.title('Validation Loss per Fold')
|
249 |
+
plt.xlabel('Fold')
|
250 |
+
plt.ylabel('Loss')
|
251 |
+
|
252 |
+
plt.tight_layout()
|
253 |
+
plt
|
254 |
+
|
255 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|