초간단 U-net 파이썬 치트코드

unet_simple

초간단버전 U-net 이해

  • 인코딩과 디코딩을 통한 Unet 초 간단버전입니다.
In [1]:
import os
from skimage.io import imread, imshow, imread_collection, concatenate_images
import numpy as np

from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Dropout, Lambda, Conv2D, Conv2DTranspose, MaxPooling2D, concatenate
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras import backend as K

import tensorflow as tf
In [2]:
train_list = os.listdir('../input/imagedata128/train/')
mask_list = os.listdir('../input/imagedata128/masks/')
In [3]:
sample = []

for file in train_list:
    sample.append( imread('../input/imagedata128/train/' + file[:100]) )
    
sample2 = []

for file in mask_list:
    sample2.append( imread('../input/imagedata128/masks/' + file[:100]) )
In [7]:
inputs = Input((128,128,1))
s = Lambda(lambda x: x / 255) (inputs)

Encoding-Decoding을 통한 딥러닝 구성

  • shape가 줄어들었다가 늘어나는것을 알수있으며,
  • concatenate를 통해 shape이 줄기 전의 정보도 계속 가지고 있음을 알수있음
In [9]:
c1 = Conv2D(filters = 16, kernel_size = (3, 3), activation = 'elu', kernel_initializer='he_normal', padding='same')(s)
c1 = Dropout(0.1)(c1)
p1 = MaxPooling2D((2,2))(c1)

c2 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p1)
c2 = Dropout(0.3) (c2)
c2 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c2)

u3 = Conv2DTranspose(filters = 16, kernel_size = (2, 2), strides=(2, 2), padding='same') (c2)
u3 = concatenate([u3, c1], axis=3)
c3 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u3)
c3 = Dropout(0.1) (c3)
c3 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c3)


outputs = Conv2D(1, (1,1), activation = 'sigmoid')(c3)
In [11]:
model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss = 'binary_crossentropy')
model.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            [(None, 128, 128, 1) 0                                            
__________________________________________________________________________________________________
lambda (Lambda)                 (None, 128, 128, 1)  0           input_1[0][0]                    
__________________________________________________________________________________________________
conv2d (Conv2D)                 (None, 128, 128, 16) 160         lambda[0][0]                     
__________________________________________________________________________________________________
dropout (Dropout)               (None, 128, 128, 16) 0           conv2d[0][0]                     
__________________________________________________________________________________________________
max_pooling2d (MaxPooling2D)    (None, 64, 64, 16)   0           dropout[0][0]                    
__________________________________________________________________________________________________
conv2d_1 (Conv2D)               (None, 64, 64, 128)  18560       max_pooling2d[0][0]              
__________________________________________________________________________________________________
dropout_1 (Dropout)             (None, 64, 64, 128)  0           conv2d_1[0][0]                   
__________________________________________________________________________________________________
conv2d_2 (Conv2D)               (None, 64, 64, 128)  147584      dropout_1[0][0]                  
__________________________________________________________________________________________________
conv2d_transpose (Conv2DTranspo (None, 128, 128, 16) 8208        conv2d_2[0][0]                   
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 128, 128, 32) 0           conv2d_transpose[0][0]           
                                                                 dropout[0][0]                    
__________________________________________________________________________________________________
conv2d_3 (Conv2D)               (None, 128, 128, 16) 4624        concatenate[0][0]                
__________________________________________________________________________________________________
dropout_2 (Dropout)             (None, 128, 128, 16) 0           conv2d_3[0][0]                   
__________________________________________________________________________________________________
conv2d_4 (Conv2D)               (None, 128, 128, 16) 2320        dropout_2[0][0]                  
__________________________________________________________________________________________________
conv2d_5 (Conv2D)               (None, 128, 128, 1)  17          conv2d_4[0][0]                   
==================================================================================================
Total params: 181,473
Trainable params: 181,473
Non-trainable params: 0
__________________________________________________________________________________________________
In [12]:
train_x = np.zeros((100, 128, 128, 1), dtype=np.uint8)
train_y = np.zeros((100, 128, 128, 1), dtype=np.uint8)
In [13]:
sample[0].shape
Out[13]:
(128, 128)
In [14]:
for index, s in enumerate(sample[:99]) :
    train_x[index] = s[:,:,np.newaxis]
    
for index, s in enumerate(sample2[:99]) :
    train_y[index] = s[:,:,np.newaxis]
In [ ]:
# Fit model
earlystopper = EarlyStopping(patience=5, verbose=1)
checkpointer = ModelCheckpoint('model-dsbowl2018-1.h5', verbose=1, save_best_only=True)
results = model.fit(train_x, train_y, validation_split=0.1, batch_size=16, epochs=50, 
                    callbacks=[earlystopper, checkpointer])

댓글 남기기