-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathex8_1_unet_cifar10.py
243 lines (200 loc) · 8.18 KB
/
ex8_1_unet_cifar10.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
#######################################################################################
# unet_conv_cifar10rgb_mc.py
# Convlutional Layer UNET with RGB Cifar10 dataset and Class with Keras Model approach
#######################################################################################
#import matplotlib
#matplotlib.use("TkAgg")
###########################
# AE 모델링
###########################
import matplotlib.pyplot as plt
from keras import models, backend
from keras.layers import Input, Conv2D, MaxPooling2D, Dropout, \
UpSampling2D, BatchNormalization, Concatenate, Activation
# backend.set_image_data_format('channels_first')
class UNET(models.Model):
def __init__(self, org_shape, n_ch):
ic = 3 if backend.image_data_format() == 'channels_last' else 1
def conv(x, n_f, mp_flag=True):
x = MaxPooling2D((2, 2), padding='same')(x) if mp_flag else x
x = Conv2D(n_f, (3, 3), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('tanh')(x)
x = Dropout(0.05)(x)
x = Conv2D(n_f, (3, 3), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('tanh')(x)
return x
def deconv_unet(x, e, n_f):
x = UpSampling2D((2, 2))(x)
x = Concatenate(axis=ic)([x, e])
x = Conv2D(n_f, (3, 3), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('tanh')(x)
x = Conv2D(n_f, (3, 3), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('tanh')(x)
return x
# Input
original = Input(shape=org_shape)
# Encoding
c1 = conv(original, 16, mp_flag=False)
c2 = conv(c1, 32)
# Encoder
encoded = conv(c2, 64)
# Decoding
x = deconv_unet(encoded, c2, 32)
x = deconv_unet(x, c1, 16)
decoded = Conv2D(n_ch, (3, 3), activation='sigmoid', padding='same')(x)
#decoded = Conv2D(n_ch, (3, 3), padding='same')(x)
super().__init__(original, decoded)
self.compile(optimizer='adadelta', loss='mse')
###########################
# 데이타 불러오기
###########################
from keras import datasets, utils
class DATA():
def __init__(self, in_ch=None):
(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
if x_train.ndim == 4:
if backend.image_data_format() == 'channels_first':
n_ch, img_rows, img_cols = x_train.shape[1:]
else:
img_rows, img_cols, n_ch = x_train.shape[1:]
else:
img_rows, img_cols = x_train.shape[1:]
n_ch = 1
# in_ch can be 1 for changing BW to color image using UNet
in_ch = n_ch if in_ch is None else in_ch
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
def RGB2Gray(X, fmt):
if fmt == 'channels_first':
R = X[:, 0:1]
G = X[:, 1:2]
B = X[:, 2:3]
else: # "channels_last
R = X[..., 0:1]
G = X[..., 1:2]
B = X[..., 2:3]
return 0.299 * R + 0.587 * G + 0.114 * B
def RGB2RG(x_train_out, x_test_out, fmt):
if fmt == 'channels_first':
x_train_in = x_train_out[:, :2]
x_test_in = x_test_out[:, :2]
else:
x_train_in = x_train_out[..., :2]
x_test_in = x_test_out[..., :2]
return x_train_in, x_test_in
if backend.image_data_format() == 'channels_first':
x_train_out = x_train.reshape(x_train.shape[0], n_ch, img_rows, img_cols)
x_test_out = x_test.reshape(x_test.shape[0], n_ch, img_rows, img_cols)
input_shape = (in_ch, img_rows, img_cols)
else:
x_train_out = x_train.reshape(x_train.shape[0], img_rows, img_cols, n_ch)
x_test_out = x_test.reshape(x_test.shape[0], img_rows, img_cols, n_ch)
input_shape = (img_rows, img_cols, in_ch)
if in_ch == 1 and n_ch == 3:
x_train_in = RGB2Gray(x_train_out, backend.image_data_format())
x_test_in = RGB2Gray(x_test_out, backend.image_data_format())
elif in_ch == 2 and n_ch == 3:
# print(in_ch, n_ch)
x_train_in, x_test_in = RGB2RG(x_train_out, x_test_out, backend.image_data_format())
else:
x_train_in = x_train_out
x_test_in = x_test_out
self.input_shape = input_shape
self.x_train_in, self.x_train_out = x_train_in, x_train_out
self.x_test_in, self.x_test_out = x_test_in, x_test_out
self.n_ch = n_ch
self.in_ch = in_ch
###########################
# UNET 검증
###########################
from keraspp.skeras import plot_loss
import matplotlib.pyplot as plt
###########################
# UNET 동작 확인
###########################
import numpy as np
from sklearn.preprocessing import minmax_scale
def show_images(data, unet):
x_test_in = data.x_test_in
x_test_out = data.x_test_out
decoded_imgs_org = unet.predict(x_test_in)
decoded_imgs = decoded_imgs_org
if backend.image_data_format() == 'channels_first':
print(x_test_out.shape)
x_test_out = x_test_out.swapaxes(1, 3).swapaxes(1, 2)
print(x_test_out.shape)
decoded_imgs = decoded_imgs.swapaxes(1, 3).swapaxes(1, 2)
if data.in_ch == 1:
x_test_in = x_test_in[:, 0, ...]
elif data.in_ch == 2:
print(x_test_out.shape)
x_test_in_tmp = np.zeros_like(x_test_out)
x_test_in = x_test_in.swapaxes(1, 3).swapaxes(1, 2)
x_test_in_tmp[..., :2] = x_test_in
x_test_in = x_test_in_tmp
else:
x_test_in = x_test_in.swapaxes(1, 3).swapaxes(1, 2)
else:
# x_test_in = x_test_in[..., 0]
if data.in_ch == 1:
x_test_in = x_test_in[..., 0]
elif data.in_ch == 2:
x_test_in_tmp = np.zeros_like(x_test_out)
x_test_in_tmp[..., :2] = x_test_in
x_test_in = x_test_in_tmp
n = 10
plt.figure(figsize=(20, 6))
for i in range(n):
ax = plt.subplot(3, n, i + 1)
if x_test_in.ndim < 4:
plt.imshow(x_test_in[i], cmap='gray')
else:
plt.imshow(x_test_in[i])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, i + 1 + n)
plt.imshow(decoded_imgs[i])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, i + 1 + n * 2)
plt.imshow(x_test_out[i])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
def main(in_ch=1, epochs=10, batch_size=512, fig=True):
###########################
# 학습 및 확인
###########################
data = DATA(in_ch=in_ch)
print(data.input_shape, data.x_train_in.shape)
unet = UNET(data.input_shape, data.n_ch)
history = unet.fit(data.x_train_in, data.x_train_out,
epochs=epochs,
batch_size=batch_size,
shuffle=True,
validation_split=0.2)
if fig:
plot_loss(history)
show_images(data, unet)
if __name__ == '__main__':
import argparse
from distutils import util
parser = argparse.ArgumentParser(description='UNET for Cifar-10: Gray to RGB')
parser.add_argument('--input_channels', type=int, default=1,
help='input channels (default: 1)')
parser.add_argument('--epochs', type=int, default=10,
help='training epochs (default: 10)')
parser.add_argument('--batch_size', type=int, default=512,
help='batch size (default: 1000)')
parser.add_argument('--fig', type=lambda x: bool(util.strtobool(x)),
default=True, help='flag to show figures (default: True)')
args = parser.parse_args()
print("Aargs:", args)
print(args.fig)
main(args.input_channels, args.epochs, args.batch_size, args.fig)