-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunet_2_with_augmentation(2).py
323 lines (255 loc) · 12.4 KB
/
unet_2_with_augmentation(2).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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# -*- coding: utf-8 -*-
"""Unet_2_with_augmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1cV-pKaeA0MceNS0w1bAnVgOhs4feJGBo
"""
from google.colab import drive
drive.mount('/content/drive')
#Import the libraries
import zipfile
import os
zip_ref = zipfile.ZipFile('/content/drive/MyDrive/dataset/input_and_masks.zip', 'r') #Opens the zip file in read mode
zip_ref.extractall('/tmp') #Extracts the files into the /tmp folder
zip_ref.close()
!pip install patchify
import numpy as np
from matplotlib import pyplot as plt
from patchify import patchify
import tifffile as tiff
image411 = tiff.imread('/tmp/input_and_masks/236102411_SIGMANAUGHT_L2A_ORBIT-7137-LEVEL-STD-MODE-MRS-POL-HH.tif')
mask411 = tiff.imread('/tmp/input_and_masks/236102411_HH_labeled6.tif')
image511 = tiff.imread('/tmp/input_and_masks/236102511_SIGMANAUGHT_L2A_ORBIT-7167-LEVEL-STD-MODE-MRS-POL-HH.tif')
mask511 = tiff.imread('/tmp/input_and_masks/236102511_HH_labeled6.tif')
image711 = tiff.imread('/tmp/input_and_masks/236102711_SIGMANAUGHT_L2A_ORBIT-7711-LEVEL-STD-MODE-MRS-POL-HH.tif')
mask711 = tiff.imread('/tmp/input_and_masks/236102711_HH_labeled6.tif')
all_img_patches = []
patches_img411 = patchify(image411, (256, 256), step=256) #Step=256 for 256 patches means no overlap
patches_img511 = patchify(image511, (256, 256), step=256)
patches_img711 = patchify(image711, (256, 256), step=256)
print(patches_img711.shape)
patches_img_name = [patches_img411, patches_img511, patches_img711 ]
for k in patches_img_name:
for i in range(k.shape[0]):
for j in range(k.shape[1]):
single_patch_img = k[i,j,:,:]
single_patch_img = (single_patch_img.astype('float16'))
all_img_patches.append(single_patch_img)
images = np.array(all_img_patches)
images = np.expand_dims(images, -1)/ images.max()
all_mask_patches = []
patches_mask411 = patchify(mask411, (256, 256), step=256) #Step=256 for 256 patches means no overlap
patches_mask511 = patchify(mask511, (256, 256), step=256)
patches_mask711 = patchify(mask711, (256, 256), step=256)
print(patches_mask711.shape)
patches_mask_name = [patches_mask411, patches_mask511, patches_mask711 ]
for k in patches_mask_name:
for i in range(k.shape[0]):
for j in range(k.shape[1]):
single_patch_mask = k[i,j,:,:]
single_patch_mask = single_patch_mask.astype('float16')
all_mask_patches.append(single_patch_mask)
masks = np.array(all_mask_patches)
masks = np.expand_dims(masks, -1)
#np.save('/content/drive/MyDrive/dataset/images', images)
#np.save('/content/drive/MyDrive/dataset/masks', masks)
# import numpy as np
# images = np.load('/content/drive/MyDrive/dataset/processed_data_unet/images.npy')
# masks = np.load('/content/drive/MyDrive/dataset/processed_data_unet/masks_cat.npy')
# masks = masks.astype('int8')
# print(images.shape)
# print(masks.shape)
print("Pixel values in the mask are: ", np.unique(masks))
print(images.max())
from keras.utils import to_categorical
n_classes = np.array([0, 1, 2, 3, 4, 5]).astype('float16')
# print(n_classes)
# from sklearn.utils import class_weight
# masks_encoded = masks.reshape(4801*256*256)
# class_weights = class_weight.compute_class_weight('balanced', classes = n_classes, y = masks_encoded)
class_weights = {0:0.6847182, 1:1.1039457, 2:1.12886027, 3:0.97458142, 4:0.74694985, 5:2.61100152}
print(class_weights)
masks_cat = to_categorical(masks, num_classes = len(n_classes), dtype = 'float16')
#np.save('/content/drive/MyDrive/dataset/masks_cat', masks_cat)
# Commented out IPython magic to ensure Python compatibility.
# %env SM_FRAMEWORK=tf.keras
!pip install segmentation_models
# u-net model
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda
from keras.optimizers import Adam
from keras.metrics import MeanIoU
import segmentation_models as sm
kernel_initializer = 'he_normal'
dice_loss = sm.losses.DiceLoss()
focal_loss = sm.losses.CategoricalFocalLoss()
total_loss = dice_loss + (1 * focal_loss)
################################################################
def simple_unet_model(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS):
#Build the model
inputs = Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))
#s = Lambda(lambda x: x / 255)(inputs) #No need for this if we normalize our inputs beforehand
s = inputs
#Contraction path
c1 = Conv2D(16, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(s)
c1 = Dropout(0.3)(c1)
c1 = Conv2D(16, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c1)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(32, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(p1)
c2 = Dropout(0.3)(c2)
c2 = Conv2D(32, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c2)
p2 = MaxPooling2D((2, 2))(c2)
c3 = Conv2D(64, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(p2)
c3 = Dropout(0.3)(c3)
c3 = Conv2D(64, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c3)
p3 = MaxPooling2D((2, 2))(c3)
c4 = Conv2D(128, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(p3)
c4 = Dropout(0.3)(c4)
c4 = Conv2D(128, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c4)
p4 = MaxPooling2D(pool_size=(2, 2))(c4)
c5 = Conv2D(256, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(p4)
c5 = Dropout(0.3)(c5)
c5 = Conv2D(256, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c5)
#Expansive path
u6 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(128, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(u6)
c6 = Dropout(0.3)(c6)
c6 = Conv2D(128, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c6)
u7 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(64, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(u7)
c7 = Dropout(0.3)(c7)
c7 = Conv2D(64, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c7)
u8 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(32, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(u8)
c8 = Dropout(0.3)(c8)
c8 = Conv2D(32, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c8)
u9 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(16, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(u9)
c9 = Dropout(0.3)(c9)
c9 = Conv2D(16, (3, 3), activation='relu', kernel_initializer=kernel_initializer, padding='same')(c9)
outputs = Conv2D(6, (1, 1), activation='softmax')(c9)
model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer=Adam(lr = 1e-4), loss= total_loss, metrics=["accuracy",sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5)])
#model.compile(optimizer=Adam(lr = 1e-3), loss='binary_crossentropy', metrics=[MeanIoU(num_classes=2)])
#model.summary()
return model
#from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(images, masks_cat, test_size = 0.25, random_state = 0)
print(X_train.shape)
print(X_test.shape)
IMG_HEIGHT = images.shape[1]
IMG_WIDTH = images.shape[2]
IMG_CHANNELS = images.shape[3]
def get_model():
return simple_unet_model(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)
model = get_model()
#Sanity check, view few mages
import random
import numpy as np
image_number = random.randint(0, len(X_train))
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.imshow(np.reshape(X_train[image_number], (256, 256)), cmap='gray')
plt.subplot(122)
plt.imshow(np.reshape(y_train[image_number], (256, 256)))
plt.show()
# #New generator with rotation and shear where interpolation that comes with rotation and shear are thresholded in masks.
# #This gives a binary mask rather than a mask with interpolated values.
# seed=24
# from keras.preprocessing.image import ImageDataGenerato
# # img_data_gen_args = dict(rotation_range=90,
# # width_shift_range=0.3,
# # height_shift_range=0.3,
# # shear_range=0.5,
# # zoom_range=0.3,
# # horizontal_flip=True,
# # vertical_flip=True,
# # fill_mode='reflect')
# # mask_data_gen_args = dict(rotation_range=90,
# # width_shift_range=0.3,
# # height_shift_range=0.3,
# # shear_range=0.5,
# # zoom_range=0.3,
# # horizontal_flip=True,
# # vertical_flip=True,
# # fill_mode='reflect',
# # preprocessing_function = lambda x: np.where(x>0, 1, 0).astype(x.dtype)) #Binarize the output again.
# image_data_generator = ImageDataGenerator()
# image_data_generator.fit(X_train, augment=False, seed=seed)
# image_generator = image_data_generator.flow(X_train, seed=seed)
# valid_img_generator = image_data_generator.flow(X_test, seed=seed)
# mask_data_generator = ImageDataGenerator()
# mask_data_generator.fit(y_train, augment=False, seed=seed)
# mask_generator = mask_data_generator.flow(y_train, seed=seed)
# valid_mask_generator = mask_data_generator.flow(y_test, seed=seed)
# def my_image_mask_generator(image_generator, mask_generator):
# train_generator = zip(image_generator, mask_generator)
# for (img, mask) in train_generator:
# yield (img, mask)
# my_generator = my_image_mask_generator(image_generator, mask_generator)
# validation_datagen = my_image_mask_generator(valid_img_generator, valid_mask_generator)
# # x = image_generator.next()
# # y = mask_generator.next()
# # for i in range(0,1):
# # image = x[i]crop01
# # mask = y[i]
# # plt.subplot(1,2,1)
# # plt.imshow(image[:,:,0], cmap='gray')
# # plt.subplot(1,2,2)
# # plt.imshow(mask[:,:,0])
# # plt.show()
# no_aug_data_train = my_image_mask_generator(X_train, y_train)
# no_aug_data_test = my_image_mask_generator(X_test, y_test)
history = model.fit(X_train, y_train, batch_size = 100, verbose = 1, validation_data=(X_test, y_test), epochs=50, shuffle = False)
# #plot the training and validation accuracy and loss at each epoch
# loss = history.history['loss']
# val_loss = history.history['val_loss']
# epochs = range(1, len(loss) + 1)
# plt.plot(epochs, loss, 'y', label='Training loss')
# plt.plot(epochs, val_loss, 'r', label='Validation loss')
# plt.title('Training and validation loss')
# plt.xlabel('Epochs')
# plt.ylabel('Loss')
# plt.legend()
# plt.show()
# acc = history.history['accuracy']
# val_acc = history.history['val_accuracy']
# plt.plot(epochs, acc, 'y', label='Training acc')
# plt.plot(epochs, val_acc, 'r', label='Validation acc')
# plt.title('Training and validation accuracy')
# plt.xlabel('Epochs')
# plt.ylabel('Accuracy')
# plt.legend()
# plt.show()
# #IOU
# y_pred=model.predict(X_test)
# y_pred_thresholded = y_pred > 0.5
# intersection = np.logical_and(y_test, y_pred_thresholded)
# union = np.logical_or(y_test, y_pred_thresholded)
# iou_score = np.sum(intersection) / np.sum(union)
# print("IoU socre is: ", iou_score)
# #Predict on a few images
# #model = get_model()
# #model.load_weights('mitochondria_50_plus_100_epochs.hdf5') #Trained for 50 epochs and then additional 100
# test_img_number = random.randint(0, len(X_test))
# test_img = X_test[test_img_number]
# ground_truth=y_test[test_img_number]
# test_img_norm=test_img[:,:,0][:,:,None]
# test_img_input=np.expand_dims(test_img_norm, 0)
# prediction = (model.predict(test_img_input)[0,:,:,0] > 0.2).astype(np.uint8)
# plt.figure(figsize=(16, 8))
# plt.subplot(231)
# plt.title('Testing Image')
# plt.imshow(test_img[:,:,0], cmap='gray')
# plt.subplot(232)
# plt.title('Testing Label')
# plt.imshow(ground_truth[:,:,0], cmap='gray')
# plt.subplot(233)
# plt.title('Prediction on test image')
# plt.imshow(prediction, cmap='gray')
# plt.show()