File size: 3,171 Bytes
68ed147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from PIL import Image
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# for image processing
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from sklearn.metrics import confusion_matrix


def validate_image(file_path):
    """Validate image integrity

        Some images are corrupted and cannot be opened by PIL

    Args:

        file_path (str): Image file path

    Returns:

        bool: True if image is valid, False otherwise"""
    
    try:
        with Image.open(file_path) as img:
            # Verify image integrity
            img.verify()
        return True
    except Exception as e:
        print(f"Corrupted image: {file_path} - Error: {e}")
        return False
    

def visualize_image(train_path, class_name="cat"):
    """Display image

    Args:

        file_path (str): Image file path

        class_name (str): Image class name

    Returns:

        10 images of the specified class"""
    
    plt.figure(figsize=(20,20))
    plt.subplots_adjust(hspace=0.4)

    for i in range(10):
        plt.subplot(1,10,i+1)
        filename = train_path +'\\'+ f'{class_name}.' + str(i) + '.jpg'
        image = Image.open(filename)
        plt.imshow(image)
        plt.title(f'{class_name}',fontsize=12)
        plt.axis('off')

    plt.show()

def visulaize_ouput(history):
    """Visualize model training output

    Args:

        history (tensorflow.python.keras.callbacks.History): Model training history

    Returns:

        plot of Loss and Accuracy"""
    
    result_df = pd.DataFrame(history.history)

    plt.figure(figsize=(18,5),dpi=200)
    sns.set_style('darkgrid')

    plt.subplot(121)
    plt.title('Cross Entropy Loss',fontsize=15)
    plt.xlabel('Epochs',fontsize=12)
    plt.ylabel('Loss',fontsize=12)
    plt.plot(result_df['loss'])
    plt.plot(result_df['val_loss'])

    plt.subplot(122)
    plt.title('Classification Accuracy',fontsize=15)
    plt.xlabel('Epochs',fontsize=12)
    plt.ylabel('Accuracy',fontsize=12)
    plt.plot(result_df['accuracy'])
    plt.plot(result_df['val_accuracy'])

    plt.show()


def predictor(model, image_path, classes, img_size=(128, 128)):
    """Predict image class

    Args:

        model (tensorflow.python.keras.engine.sequential.Sequential): Model

        image_path (str): Image file path

        classes (list): List of class names

        img_size (tuple): Image size

    Returns:

        Image class prediction with plots"""
    
    img = load_img(image_path, target_size=img_size)  
    img_array = img_to_array(img) / 255.0 
    img_array = np.expand_dims(img_array, axis=0)

    predictions = model.predict(img_array)
    predicted_class = np.argmax(predictions, axis=1)[0] 
    print(predictions)
    print(predicted_class)
    confidence = predictions[0][predicted_class]
    print(confidence)
    if confidence > 0.5:
        predicted_class = 1
    else:
        predicted_class = 0
    
    plt.imshow(img)
    plt.axis('off')
    plt.title(f"Prediction: {classes[predicted_class]}")
    plt.show()