-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestScript.py
More file actions
58 lines (41 loc) · 1.38 KB
/
testScript.py
File metadata and controls
58 lines (41 loc) · 1.38 KB
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
import tensorflow as tf
import numpy as np
import os
import pandas as pd
from PIL import Image
IMG_SIZE = (224, 224)
test_dir = ""
output_csv = "./Submissions/ResNet_submission.csv"
IMAGENET_MEAN = tf.constant([103.939, 116.779, 123.68], dtype=tf.float32)
def preprocess_input_resnet(x):
x = tf.cast(x, tf.float32)
x = x[..., ::-1]
x = x - IMAGENET_MEAN
return x
model_path = "Models\my_model.keras"
model = tf.keras.models.load_model(model_path)
print("Model loaded successfully!")
results = []
image_files = sorted(os.listdir(test_dir))
pred_classes_so_far = []
for img_name in image_files:
img_path = os.path.join(test_dir, img_name)
try:
img = Image.open(img_path).convert("RGB")
img = img.resize(IMG_SIZE)
x = np.array(img, dtype=np.float32)
x = np.expand_dims(x, axis=0)
x = preprocess_input_resnet(x)
pred = model.predict(x, verbose=0)
pred_class = int(np.argmax(pred))
pred_classes_so_far.append(pred_class)
except Exception as e:
print(f"Skipping {img_name}: {e}")
if pred_classes_so_far:
pred_class = int(pred_classes_so_far[-1])
else:
pred_class = 0
results.append([img_name, pred_class])
df = pd.DataFrame(results, columns=["ImageName", "ClassLabel"])
df.to_csv(output_csv, index=False)
print(f"Saved predictions to {output_csv}")