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