utils.py 5.73 KB
Newer Older
Martin Lank's avatar
Martin Lank committed
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
import json
import pathlib

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
from sklearn.metrics import classification_report
from sklearn.utils import class_weight



DATASET_DEFAULT_V3_TRAIN = "default_v3_train"
DATASET_DEFAULT_V3_TEST = "default_v3_test"


def get_dataset_dir(dataset):
  
    if dataset == DATASET_DEFAULT_V3_TRAIN:
        return "export_v3_train"
    elif dataset == DATASET_DEFAULT_V3_TEST:
        return "export_v3_test"   
    else:
        raise Exception("Unknown dataset: " + dataset)

def load_data(dataset, batch_size, cache_prefetch=True, colorspace="rgb", validation_split=0.25):
    if dataset == DATASET_DEFAULT_V3_TEST:
        img_height = 480
        img_width = 640

        data_dir = pathlib.Path('./data/' + get_dataset_dir(dataset))

        val_ds = tf.keras.preprocessing.image_dataset_from_directory(
            data_dir,
            seed=123,
            color_mode=colorspace,
            image_size=(img_height, img_width),
            batch_size=batch_size)

        names = val_ds.class_names
        val_ds = val_ds.cache().prefetch(buffer_size=-1)

        return None, val_ds, names, 0, 0, None
    elif dataset == DATASET_DEFAULT_V3_TRAIN in dataset:
        img_height = 480
        img_width = 640

        data_dir = pathlib.Path('./data/' + get_dataset_dir(dataset))

        train_ds = tf.keras.preprocessing.image_dataset_from_directory(
            data_dir,
            validation_split=validation_split,
            subset=None if validation_split is None else "training",
            seed=123,
            color_mode=colorspace,
            image_size=(img_height, img_width),
            batch_size=batch_size)

        if validation_split is not None:
            val_ds = tf.keras.preprocessing.image_dataset_from_directory(
                data_dir,
                validation_split=validation_split,
                subset="validation",
                seed=123,
                color_mode=colorspace,
                image_size=(img_height, img_width),
                batch_size=batch_size)
        else:
            val_ds = None

        class_weights = calculate_weight(data_dir, validation_split)
    
    else:
        raise Exception("Unsupported dataset type.")

    class_names = train_ds.class_names
    train_len = len(np.concatenate([y for x, y in train_ds], axis=0))
    val_len = len(np.concatenate([y for x, y in val_ds], axis=0)) if validation_split is not None else 0

    if cache_prefetch:
        train_ds = train_ds.cache().shuffle(train_len).prefetch(buffer_size=-1)
        if validation_split is not None:
            val_ds = val_ds.cache().prefetch(buffer_size=-1)

    return train_ds, val_ds, class_names, train_len, val_len, class_weights


def calculate_weight(train_directory, validation_split):
    datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split=validation_split).flow_from_directory(
        train_directory,
        target_size=(10, 10),
        batch_size=32,
        class_mode="categorical"
    )

    weights = class_weight.compute_class_weight('balanced', classes=np.unique(datagen.classes), y=datagen.classes)
    return {i: weights[i] for i in range(len(weights))}


def generate_plots(history, epochs, folder, experiment_number, show=False):
    acc = history.history['accuracy']
    loss = history.history['loss']

    if 'val_accuracy' in history.history:
        val_acc = history.history['val_accuracy']
        val_loss = history.history['val_loss']

    epochs_range = range(min(epochs, len(acc)))  # prevent exception when early stop canceles learning

    plt.figure(figsize=(8, 8))
    plt.subplot(1, 2, 1)
    plt.plot(epochs_range, acc, label='Training Accuracy')
    if 'val_accuracy' in history.history:
        plt.plot(epochs_range, val_acc, label='Validation Accuracy')
    plt.legend(loc='lower right')
    # plt.ylim((0.6, 0.9))
    plt.title('Training and Validation Accuracy')

    plt.subplot(1, 2, 2)
    plt.plot(epochs_range, loss, label='Training Loss')
    if 'val_accuracy' in history.history:
        plt.plot(epochs_range, val_loss, label='Validation Loss')
    plt.legend(loc='upper right')
    plt.title('Training and Validation Loss')
    # plt.ylim((0.75, 1.6))
    plt.savefig(folder + '/accuracy_over_epochs_' + str(experiment_number) + '.jpg')
    if show:
        plt.show()

    print("Plots saved.")


def generate_report(model, folder, val_ds, class_names, experiment_number, save=True):
    y_pred = np.argmax(model.predict(val_ds), axis=-1)
    y_val = np.concatenate([y for x, y in val_ds], axis=0)
    report_dict = classification_report(y_val, y_pred, target_names=class_names, output_dict=True)
    df = pd.DataFrame(report_dict).transpose()
    if save:
        df.to_csv(folder + "/report_" + str(experiment_number) + ".csv", sep=";")
        print("Report of exp. " + str(experiment_number) + " saved.")
    print("Report of experiment " + str(experiment_number),
          classification_report(y_val, y_pred, target_names=class_names))
    return df


def save_architecture(model, folder, experiment_number):
    tf.keras.utils.plot_model(
        model,
        to_file=folder + "/model_" + str(experiment_number) + ".png",
        show_shapes=True,
        show_layer_names=True,
        rankdir="TB",
        expand_nested=False,
        dpi=96,
    )

    with open(folder + '/architecture_' + str(experiment_number) + '.json', 'w') as outfile:
        json.dump(model.to_json(), outfile)

    print("Architecture saved.")


def load_architecture(folder, experiment_number):
    with open(folder + '/architecture_' + str(experiment_number) + '.json', 'r') as infile:
        data = json.load(infile)
        return tf.keras.models.model_from_json(data,custom_objects={'KerasLayer':hub.KerasLayer})