File size: 3,801 Bytes
a44aa14 45a1db8 a44aa14 45a1db8 a44aa14 |
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 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 |
# -*- coding: utf-8 -*-
"""
Created on Fri May 24 14:31:20 2024
@author: beni
"""
###test on art 30 epoches
###Test Loss: 0.7387489676475525
#Test Accuracy: 0.8525179624557495 ELA_CNN_ART.h5
####
#####test on objects
###ELA_CNN_OBJ.h5
#Test Loss: 1.260271430015564
#Test Accuracy: 0.5509259104728699
from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, Dropout, Flatten, Dense
from project_cnn_ela import convert_to_ela_image, shuffle_and_split_data, labeling
import pandas as pd
import numpy as np
from PIL import Image
import os
from pylab import *
import re
from PIL import Image, ImageChops, ImageEnhance
import tensorflow as tf
import itertools
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers.legacy import RMSprop
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from copy import deepcopy
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'valid',
activation ='relu', input_shape = (128,128,3)))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'valid',
activation ='relu'))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(2, activation = "softmax"))
model.summary()
# Load saved weights
model.load_weights("ELA_CNN_ART_V2.h5")
optimizer = RMSprop(lr=0.0005, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"])
test_real_folder = 'datasets/test_set/real/'
test_fake_folder = 'datasets/test_set/fake/'
test_ela_output = 'datasets/training_set/ela_output/'
test_set = labeling(test_real_folder, test_fake_folder)
X_test = []
Y_test = []
# Preprocess test set
for index, row in test_set.iterrows():
X_test.append(array(convert_to_ela_image(row[0], 90, test_ela_output).resize((128, 128))).flatten() / 255.0)
Y_test.append(row[1])
# Convert to numpy arrays
X_test = np.array(X_test)
Y_test = to_categorical(Y_test, 2)
# Reshape images
X_test = X_test.reshape(-1, 128, 128, 3)
# Evaluate the model on test set
test_loss, test_accuracy = model.evaluate(X_test, Y_test)
print()
print("~~~~~art Dataset~~~~")
print()
print("Test Loss:", test_loss)
print("Test Accuracy:", test_accuracy)
#######################################################
def calculate_acc(y_true, y_pred):
# Calculate precision
precision = precision_score(y_true, y_pred)
# Calculate recall
recall = recall_score(y_true, y_pred)
# Calculate F1 score
f1 = f1_score(y_true, y_pred)
# Calculate confusion matrix
conf_matrix = confusion_matrix(y_true, y_pred)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("Confusion Matrix:")
# Plot confusion matrix
plt.figure(figsize=(8, 6))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', cbar=False)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()
# Get predicted probabilities
Y_pred_prob = model.predict(X_test)
# Convert predicted probabilities to class labels
Y_pred = np.argmax(Y_pred_prob, axis=1)
Y_true = np.argmax(Y_test, axis=1)
# Calculate accuracies
calculate_acc(Y_true, Y_pred)
model.summary()
|