-
Notifications
You must be signed in to change notification settings - Fork 3
/
class_nn_siamese.py
206 lines (168 loc) · 6.49 KB
/
class_nn_siamese.py
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from keras import backend as K
from keras.models import Model
from keras.regularizers import l2
from keras.optimizers import Adam
from keras.initializers import he_uniform, he_normal
from keras.layers import Input, Dense, LeakyReLU, Lambda
class nn_siamese:
###########################################################################################
# Constructor #
###########################################################################################
def __init__(
self,
layer_dims, # [n_x, n_h1, .., n_hL] - at least one hidden layer
learning_rate,
num_epochs,
weight_init='he_normal',
output_activation='sigmoid',
loss_function='binary_crossentropy',
minibatch_size=64,
l2=0.0,
distance_metric='abs',
seed=0
):
# seed
self.seed = seed
# NN parameters
self.layer_dims = layer_dims
self.learning_rate = learning_rate
self.num_epochs = num_epochs
self.output_activation = output_activation
self.loss_function = loss_function
self.minibatch_size = minibatch_size
self.l2 = l2
self.distance_metric = distance_metric
if weight_init == 'he_uniform':
self.weight_init = he_uniform(seed=self.seed)
elif weight_init == 'he_normal':
self.weight_init = he_normal(seed=self.seed)
# model
self.model = self.create_siamese_model()
# self.model.summary()
# configure model for training
self.model.compile(
optimizer=Adam(lr=self.learning_rate),
loss=self.loss_function,
metrics=['accuracy']
)
###########################################################################################
# Auxiliary #
###########################################################################################
#################
# Siamese model #
#################
def create_siamese_model(self):
siamese_base = self.create_siamese_base()
input_left = Input(shape=(self.layer_dims[0],))
input_right = Input(shape=(self.layer_dims[0],))
encoded_left = siamese_base(input_left)
encoded_right = siamese_base(input_right)
# Add a customized layer to compute the distance between the encodings
if self.distance_metric == 'abs':
lambda_layer = Lambda(lambda tensors: K.abs(tensors[0] - tensors[1]), name='abs')
elif self.distance_metric == 'chi2':
lambda_layer = Lambda(lambda tensors: (tensors[0] - tensors[1])**2 / (tensors[0] + tensors[1]), name='chi2')
distance = lambda_layer([encoded_left, encoded_right])
# Add a dense layer with a sigmoid unit to generate the similarity score
X_output = Dense(
units=1,
activation='sigmoid',
use_bias=True,
kernel_initializer=self.weight_init,
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None
)(distance)
# Connect the inputs with the outputs
return Model(inputs=[input_left, input_right], outputs=X_output)
################
# Siamese base #
################
def create_siamese_base(self):
# Input dims
n_x = self.layer_dims[0]
# Input layer
X_input = Input(shape=(n_x,), name='input')
# First hidden layer
X = Dense(
units=self.layer_dims[1],
activation=None,
use_bias=True,
kernel_initializer=self.weight_init,
bias_initializer='zeros',
kernel_regularizer=l2(self.l2),
bias_regularizer=None,
activity_regularizer=None
)(X_input)
X = LeakyReLU(alpha=0.01)(X)
# Other hidden layers (if any)
for l in self.layer_dims[2:]:
X = Dense(
units=l,
activation=None,
use_bias=True,
kernel_initializer=self.weight_init,
bias_initializer='zeros',
kernel_regularizer=l2(self.l2),
bias_regularizer=None,
activity_regularizer=None
)(X)
X = LeakyReLU(alpha=0.01)(X)
return Model(inputs=X_input, outputs=X)
########
# Plot #
########
def plot_learning_curves(self, history, flag_val):
# Plot accuracy values
plt.plot(history.history['accuracy'])
if flag_val:
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()
# Plot loss values
plt.plot(history.history['loss'])
if flag_val:
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()
###########################################################################################
# API #
###########################################################################################
##############
# Prediction #
##############
def predict(self, x):
# probability prediction
y_hat = self.model.predict(x=x, verbose=0)
return y_hat
############
# Training #
############
def train(self, x, y, validation_data=None):
history = self.model.fit(
x=x,
y=y,
validation_data=validation_data,
epochs=self.num_epochs,
batch_size=self.minibatch_size,
shuffle=False,
verbose=0 # 0: off, 1: full, 2: brief
)
flag_val = False if validation_data is None else True
acc = history.history['accuracy'][-1]
loss = history.history['loss'][-1]
if flag_val:
val_acc = history.history['val_accuracy'][-1]
val_loss = history.history['val_loss'][-1]
return loss, acc, val_loss, val_acc
else:
return loss, acc