Update vit_model_test.py
Browse files- vit_model_test.py +61 -36
vit_model_test.py
CHANGED
@@ -1,15 +1,32 @@
|
|
1 |
import torch
|
2 |
import torch.nn as nn
|
3 |
-
import torch.nn.functional as F
|
4 |
from torch.utils.data import Dataset, DataLoader
|
5 |
from torchvision import transforms
|
6 |
from transformers import ViTForImageClassification
|
7 |
from PIL import Image
|
8 |
import os
|
9 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
|
|
12 |
|
|
|
13 |
|
14 |
class CustomDataset(Dataset):
|
15 |
def __init__(self, dataframe, transform=None):
|
@@ -26,9 +43,19 @@ class CustomDataset(Dataset):
|
|
26 |
if self.transform:
|
27 |
image = self.transform(image)
|
28 |
|
29 |
-
|
|
|
30 |
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
if __name__ == "__main__":
|
33 |
# Check for GPU availability
|
34 |
device = torch.device('cuda')
|
@@ -45,25 +72,11 @@ if __name__ == "__main__":
|
|
45 |
transforms.ToTensor()
|
46 |
])
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
# Load the test dataset
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
test_set = 'datasets/'
|
58 |
-
|
59 |
-
image_paths = []
|
60 |
-
for filename in os.listdir(test_set):
|
61 |
-
image_paths.append(os.path.join(test_set, filename))
|
62 |
-
dataset = pd.DataFrame({'image_path': image_paths})
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
test_dataset = CustomDataset(dataset, transform=preprocess)
|
67 |
test_loader = DataLoader(test_dataset, batch_size=32)
|
68 |
|
69 |
# Load the trained model
|
@@ -71,25 +84,37 @@ if __name__ == "__main__":
|
|
71 |
|
72 |
# Evaluate the model
|
73 |
model.eval()
|
74 |
-
|
75 |
predicted_labels = []
|
76 |
-
|
77 |
|
78 |
with torch.no_grad():
|
79 |
-
for images in test_loader:
|
80 |
-
images = images.to(device)
|
81 |
outputs = model(images)
|
82 |
logits = outputs.logits # Extract logits from the output
|
83 |
-
|
84 |
-
|
85 |
predicted_labels.extend(predicted.cpu().numpy())
|
86 |
-
confidences.extend(confidences_per_image.cpu().numpy())
|
87 |
-
|
88 |
-
|
89 |
-
print(predicted_labels)
|
90 |
-
print(confidences)
|
91 |
-
|
92 |
-
confidence_percentages = [confidence * 100 for confidence in confidences]
|
93 |
-
for label, confidence in zip(predicted_labels, confidence_percentages):
|
94 |
-
print(f"Predicted label: {label}, Confidence: {confidence:.2f}%")
|
95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import torch
|
2 |
import torch.nn as nn
|
|
|
3 |
from torch.utils.data import Dataset, DataLoader
|
4 |
from torchvision import transforms
|
5 |
from transformers import ViTForImageClassification
|
6 |
from PIL import Image
|
7 |
import os
|
8 |
import pandas as pd
|
9 |
+
from sklearn.model_selection import train_test_split
|
10 |
+
from sklearn.metrics import accuracy_score, precision_score, confusion_matrix, f1_score, average_precision_score
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
import seaborn as sns
|
13 |
+
from sklearn.metrics import recall_score
|
14 |
|
15 |
+
def labeling(path_real, path_fake):
|
16 |
+
image_paths = []
|
17 |
+
labels = []
|
18 |
+
|
19 |
+
for filename in os.listdir(path_real):
|
20 |
+
image_paths.append(os.path.join(path_real, filename))
|
21 |
+
labels.append(0)
|
22 |
+
|
23 |
+
for filename in os.listdir(path_fake):
|
24 |
+
image_paths.append(os.path.join(path_fake, filename))
|
25 |
+
labels.append(1)
|
26 |
|
27 |
+
dataset = pd.DataFrame({'image_path': image_paths, 'label': labels})
|
28 |
|
29 |
+
return dataset
|
30 |
|
31 |
class CustomDataset(Dataset):
|
32 |
def __init__(self, dataframe, transform=None):
|
|
|
43 |
if self.transform:
|
44 |
image = self.transform(image)
|
45 |
|
46 |
+
label = self.dataframe.iloc[idx, 1] # Label is in the second column
|
47 |
+
return image, label
|
48 |
|
49 |
+
def shuffle_and_split_data(dataframe, test_size=0.2, random_state=59):
|
50 |
+
# Shuffle the DataFrame
|
51 |
+
shuffled_df = dataframe.sample(frac=1, random_state=random_state).reset_index(drop=True)
|
52 |
+
|
53 |
+
# Split the DataFrame into train and validation sets
|
54 |
+
train_df, val_df = train_test_split(shuffled_df, test_size=test_size, random_state=random_state)
|
55 |
+
|
56 |
+
return train_df, val_df
|
57 |
+
|
58 |
+
|
59 |
if __name__ == "__main__":
|
60 |
# Check for GPU availability
|
61 |
device = torch.device('cuda')
|
|
|
72 |
transforms.ToTensor()
|
73 |
])
|
74 |
|
|
|
|
|
|
|
|
|
75 |
# Load the test dataset
|
76 |
+
test_real_folder = 'test/art/real'
|
77 |
+
test_fake_folder = 'test/art/fake'
|
78 |
+
test_set = labeling(test_real_folder, test_fake_folder)
|
79 |
+
test_dataset = CustomDataset(test_set, transform=preprocess)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
test_loader = DataLoader(test_dataset, batch_size=32)
|
81 |
|
82 |
# Load the trained model
|
|
|
84 |
|
85 |
# Evaluate the model
|
86 |
model.eval()
|
87 |
+
true_labels = []
|
88 |
predicted_labels = []
|
|
|
89 |
|
90 |
with torch.no_grad():
|
91 |
+
for images, labels in test_loader:
|
92 |
+
images, labels = images.to(device), labels.to(device)
|
93 |
outputs = model(images)
|
94 |
logits = outputs.logits # Extract logits from the output
|
95 |
+
_, predicted = torch.max(logits, 1)
|
96 |
+
true_labels.extend(labels.cpu().numpy())
|
97 |
predicted_labels.extend(predicted.cpu().numpy())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
|
99 |
+
# Calculate evaluation metrics
|
100 |
+
accuracy = accuracy_score(true_labels, predicted_labels)
|
101 |
+
precision = precision_score(true_labels, predicted_labels)
|
102 |
+
cm = confusion_matrix(true_labels, predicted_labels)
|
103 |
+
f1 = f1_score(true_labels, predicted_labels)
|
104 |
+
ap = average_precision_score(true_labels, predicted_labels)
|
105 |
+
recall = recall_score(true_labels, predicted_labels)
|
106 |
+
|
107 |
+
|
108 |
+
print(f"Test Accuracy: {accuracy:.2%}")
|
109 |
+
print(f"Precision: {precision:.2%}")
|
110 |
+
print(f"F1 Score: {f1:.2%}")
|
111 |
+
print(f"Average Precision: {ap:.2%}")
|
112 |
+
print(f"Recall: {recall:.2%}")
|
113 |
+
|
114 |
+
# Plot the confusion matrix
|
115 |
+
plt.figure(figsize=(8, 6))
|
116 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False)
|
117 |
+
plt.xlabel('Predicted Labels')
|
118 |
+
plt.ylabel('True Labels')
|
119 |
+
plt.title('Confusion Matrix')
|
120 |
+
plt.show()
|