-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel.py
245 lines (188 loc) · 8.86 KB
/
model.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
Convolutional auto-encoder model to clean microscope images.
"""
import time
import tensorflow as tf
import os
import sklearn
import numpy as np
class ImageCleaner(object):
def __init__(self):
self.dropout = 0.2
self.lr = 0.001
self.is_training = False
tf.reset_default_graph()
self.build()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
self.val_error = []
self.val_loss = []
def build(self):
'''
Build tensorflow computation graph
'''
# Input placeholders
self.input_img = tf.placeholder(tf.float32, (None,64,64,1))
self.target_img = tf.placeholder(tf.float32, (None,64,64,1))
# Layer 1: Conv to 32x32x15
conv1 = tf.layers.conv2d(inputs=self.input_img,
filters=15,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Dropout layer
drop1 = tf.layers.dropout(inputs=conv1,
rate=self.dropout,
training=self.is_training)
# Layer 2: Conv to 16x16x30
conv2 = tf.layers.conv2d(inputs=drop1,
filters=30,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Layer 3: Conv to 8x8x45
conv3 = tf.layers.conv2d(inputs=conv2,
filters=45,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Layer 4: Conv_transpose to 16x16x45
conv_t4 = tf.layers.conv2d_transpose(inputs=conv3,
filters=45,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Layer 5: Conv_transpose to 32x32x30
conv_t5 = tf.layers.conv2d_transpose(inputs=conv_t4,
filters=30,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Layer 6: Conv_transpose to 64x64x15
conv_t6 = tf.layers.conv2d_transpose(inputs=conv_t5,
filters=15,
kernel_size=(5,5),
strides=(2,2),
padding='same',
activation=tf.nn.relu)
# Layer 7: Conv_transpose to 128x128x10
conv_t7 = tf.layers.conv2d_transpose(inputs=conv_t6,
filters=10,
kernel_size=(5,5),
strides=(1,1),
padding='same',
activation=tf.nn.relu)
# Layer 8: Conv to 64x64x1
conv8 = tf.layers.conv2d(inputs=conv_t7,
filters=1,
kernel_size=(3,3),
strides =(1,1),
padding='same',
activation=None)
# Make logits
logits = tf.slice(conv8, [0, 0, 0, 0], [-1, 64, 64, 1])
# Pass logits through sigmoid to get reconstructed image
self.decoded_img = tf.nn.sigmoid(logits)
# Pass logits through sigmoid and calculate the cross-entropy
entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=self.target_img,
logits=logits)
# Get loss and define the optimizer
self.loss = tf.reduce_mean(entropy)
self.opt = tf.train.AdamOptimizer(self.lr).minimize(self.loss)
# Error(average image intensity difference)
img_diff = tf.math.sqrt(tf.math.square(self.decoded_img
- self.target_img))
self.error = tf.reduce_mean(img_diff)
def evaluate(self, x=None, y=None, batch_size=20, save_results=False):
'''
Evaluate a model
'''
total_loss, total_error = 0, 0
self.is_training = False
for i in range(x.shape[0]//batch_size):
x_batch = x[i*batch_size:(i+1)*batch_size,:,:,:]
y_batch = y[i*batch_size:(i+1)*batch_size,:,:,:]
l, error = self.sess.run([self.loss, self.error],
feed_dict={self.input_img:x_batch,
self.target_img:y_batch})
total_loss += l
total_error += error
mean_loss = total_loss/(i+1)
mean_error = total_error/(i+1)
print('Validation loss: {:.4f} - Validation Error: {:.4f}'.format(
mean_loss, mean_error))
if save_results:
self.val_loss.append(mean_loss)
self.val_error.append(mean_error)
def fit(self, x=None, y=None, batch_size=20, epochs=1, verbose=1,
shuffle=True, val_x=None, val_y=None, initial_epoch=0,
save_path=None):
'''
The train function with api similar to Keras
'''
# Make dir for checkpoints if doesn't exist
if save_path:
if not os.path.exists(os.path.dirname(save_path)):
os.makedirs(os.path.dirname(save_path))
saver = tf.train.Saver()
# Initialize to store training parameters
self.train_epoch = []
self.train_loss = []
self.train_error = []
if np.any(val_x):
self.val_loss = []
self.val_error = []
for e in range(initial_epoch, epochs+initial_epoch):
# start_time = time.time()
if shuffle:
x, y = sklearn.utils.shuffle(x, y)
print('Epoch {:}/{:}'.format(e+1, epochs+initial_epoch))
progbar = tf.keras.utils.Progbar(x.shape[0], verbose=verbose)
total_loss, total_error = 0, 0
self.is_training = True
for i in range(x.shape[0]//batch_size):
x_batch = x[i*batch_size:(i+1)*batch_size,:,:,:]
y_batch = y[i*batch_size:(i+1)*batch_size,:,:,:]
l, _, error = self.sess.run([self.loss, self.opt, self.error],
feed_dict={self.input_img:x_batch,
self.target_img:y_batch})
progbar.add(x_batch.shape[0], values=[("Loss", l),
("Error", error)])
total_loss += l
total_error += error
self.train_epoch.append(e+1)
self.train_loss.append(total_loss/(i+1))
self.train_error.append(total_error/(i+1))
# Perform Validation
if np.any(val_x):
self.evaluate(x=val_x, y=val_y,
batch_size=batch_size, save_results=True)
if save_path:
saver.save(self.sess, save_path, global_step=e)
# print('Time elapsed in current iteration: {:.2f} seconds'.format(
# time.time() - start_time))
def predict(self, x=None, batch_size=20):
'''
Predict a model
'''
self.is_training = False
y = np.zeros(x.shape)
for i in range(x.shape[0]//batch_size):
x_batch = x[i*batch_size:(i+1)*batch_size,:,:,:]
predicted_img = self.sess.run([self.decoded_img],
feed_dict={self.input_img:x_batch})
y[i*batch_size:(i+1)*batch_size,:,:,:] = np.asarray(predicted_img[0])
return y
def save(self, save_path='./final_model/my_model.ckpt'):
saver = tf.train.Saver()
saver.save(self.sess, save_path)
print("Model saved in path: %s" % save_path)
def restore(self, save_path='./final_model/my_model.ckpt'):
saver = tf.train.Saver()
saver.restore(self.sess, save_path)
print("Model restored.")