File size: 2,078 Bytes
e2a99cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
from keras.utils import image_dataset_from_directory

train_dir="/media/data/plants_diseases_dataset/train"
val_dir="/media/data/plants_diseases_dataset/valid"
img_size=(224,224)
batch_size=32

train_ds=image_dataset_from_directory(train_dir,
                                      image_size=img_size,
                                      batch_size=batch_size,
                                      label_mode="categorical")

val_ds=image_dataset_from_directory(val_dir,
                                      image_size=img_size,
                                      batch_size=batch_size,
                                      label_mode="categorical")
def evaluate_model(model, dataset, class_names):
    """
    Evaluate a trained Keras model on a dataset.

    Args:
        model: Trained Keras model
        dataset: tf.data.Dataset (e.g. val_ds)
        class_names: list of class names
    """

    # Get predictions and true labels
    y_true = []
    y_pred = []

    for batch in dataset:
        images, labels = batch
        preds = model.predict(images)
        y_true.extend(np.argmax(labels.numpy(), axis=1))
        y_pred.extend(np.argmax(preds, axis=1))

    # Classification report
    print("\n--- Classification Report ---")
    print(classification_report(y_true, y_pred, target_names=class_names))

    # Confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    plt.figure(figsize=(10, 8))
    sns.heatmap(cm, annot=False, cmap="Blues", xticklabels=class_names, yticklabels=class_names)
    plt.title("Confusion Matrix")
    plt.xlabel("Predicted")
    plt.ylabel("True")
    plt.show()

    # Overall accuracy
    acc = np.mean(np.array(y_true) == np.array(y_pred))
    print(f"\n Accuracy: {acc*100:.2f}%")

from keras.models import load_model
from keras.applications import mobilenet_v3


model = load_model("models/mobileNet_1.keras")
evaluate_model(model, val_ds, class_names=train_ds.class_names)