To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

custom_callbacks.py 5.04 KB
Newer Older
matthmey's avatar
matthmey 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
"""
Script for the paper "Systematic Identification of External Influences in Multi-Year Micro-Seismic Recordings Using Convolutional Neural Networks"

Custom keras callback function to save the best instance

Copyright (c) 2018, Swiss Federal Institute of Technology (ETH Zurich)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import numpy as np 

from aednn.toolbox import evaluate

import keras

class MetricPlot(keras.callbacks.Callback):
    def __init__(self,filename,names=['loss']):
        self.filename = filename
        self.names = names
        self.fig, self.ax = plt.subplots(len(self.names),1)

    def on_train_begin(self, logs={}):
        self.logs = {}

    def on_batch_end(self, batch, logs={}):
        pass

    def append_log(self,name,logs):
        if name not in self.logs:
            self.logs[name] = []
        self.logs[name].append(logs.get(name))

    def on_epoch_end(self, batch, logs={}): 
        plt.figure(self.fig.number)
        for idx,name in enumerate(self.names):
            self.append_log(name,logs)
            self.append_log('val_' + name,logs)

            self.ax[idx].plot(self.logs[name],'r')
            self.ax[idx].plot(self.logs['val_'+name],'b')
            self.ax[idx].set_title('%s (train:red val:blue)'%name)

        plt.savefig(self.filename,dpi=300)


class SaveBest(keras.callbacks.Callback):
    def __init__(self,filename,X_val,y_val,indices=None):
        """Performs evaluation and saves the model if it exceeds the best value
        
        Arguments:
            keras {[type]} -- [description]
            filename {[type]} -- [description]
            X_val {[type]} -- [description]
            y_val {[type]} -- [description]
            indices {list or None} -- List of indices. If None the scores for all labels will be compared, else only labels given by the indices
        """

        self.X_val = X_val
        self.y_val = y_val
        self.filename = filename
        self.best_eval = 0
        if indices is None:
            self.indices = np.arange(y_val.shape[1])
        else:
            self.indices = np.array(indices)

    def on_train_begin(self, logs={}):
        self.logs = {}

    def on_batch_end(self, batch, logs={}):
        pass

    def on_epoch_end(self, batch, logs={}): 
        y_pred = self.model.predict(self.X_val,batch_size=16)
        eval_results, thresholds = evaluate(self.y_val[:,self.indices],y_pred[:,self.indices],eval_best='f1score',return_thresholds=True)
        if eval_results['f1score'] > self.best_eval:
            self.best_eval = eval_results['f1score']
            self.model.save(self.filename, overwrite=True)

        print(eval_results['f1score'],thresholds,self.best_eval)


class myCallbackPlot(keras.callbacks.Callback):
    def __init__(self, filename,names=['loss']):
        self.filename = filename
        self.names = names
        self.fig, self.ax = plt.subplots(len(self.names), 1)

    def on_train_begin(self, logs={}):
        self.logs = {}

    def on_batch_end(self, batch, logs={}):
        pass

    def append_log(self, name, logs):
        if name not in self.logs:
            self.logs[name] = []
        self.logs[name].append(logs.get(name))

    def on_epoch_end(self, batch, logs={}):
        plt.figure(self.fig.number)
        for idx, name in enumerate(self.names):
            self.append_log(name, logs)
            self.append_log('val_' + name, logs)

            self.ax[idx].plot(self.logs[name], 'r')
            self.ax[idx].plot(self.logs['val_'+ name],'b')
            self.ax[idx].set_title('%s (train:red val:blue)'%name)

        plt.savefig(self.filename, fdpi=300, format='eps')