Convolutional Neural Networks in TensorFlow week3

han811·2020년 11월 12일
0
post-thumbnail

Transfer Learning

tensorflow transfer learning tutorial docu
https://www.tensorflow.org/tutorials/images/transfer_learning

[주요 코드 리뷰]

from tensorflow.keras.applications.inception_v3 import InceptionV3

local_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'

pre_trained_model = InceptionV3(input_shape = (150, 150, 3), 
                                include_top = False, 
                                weights = None)

pre_trained_model.load_weights(local_weights_file)

for layer in pre_trained_model.layers:
  layer.trainable = False
  
# pre_trained_model.summary()

last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape: ', last_layer.output_shape)
last_output = last_layer.output

# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = layers.Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)                  
# Add a final sigmoid layer for classification
x = layers.Dense  (1, activation='sigmoid')(x)           

model = Model( pre_trained_model.input, x) 

tf.keras.applications 모듈에는 자주 사용되는 아키텍쳐들이 구현되어 있다.
official docu link
https://www.tensorflow.org/api_docs/python/tf/keras/applications?hl=ko
해당 모듈을 불러와서 input_shape만 지정해주면 바로 사용이 가능하다.
이때 include_top 옵션은 최상단에 fully connected layer를 같이 불러올지 빼고 불러올지를 결정한다.
만약 include_top 옵션이 default인 true라면 input_shape을 정해진 것중에서 골라야한다.
보통 기본 input이거나 channel이 바깥으로오는 역순으로 넣는 것이 전부가 된다.
weights는 특정 이미지 데이터 대회의 weight를 적용할지 안할지를 결정하는 인자로 None이라서 웨이트가 초기화 된채 모델이 불러와진다.

load_weights는 h5로 된 weight파일을 해당 모델에 load하는 역할을 하는 method 이다.

각 layer들은 trainable이라는 attribute를 가지며 해당 attribute가 False이면 weight가 update되지 않는다.

get_layer는 특정 layer를 layer name으로 불러오는 method이다.

tf.keras.Model은 inputs과 outputs를 지정해주는 것으로 새로히 모델을 만들 수 있다.

x = layers.Dropout(0.2)(x)  

이때 transfer learning에서는 이 dropout을 넣냐 안넣는냐가 큰 성능의 차이를 가져온다.
아무래도 dropout이 주변의 weight들이 서로 동화되는 현상을 어느정도 막아주므로 새로운 x data에 대한 학습이 더 잘 이루어지는 것 같다.

my github repo - https://github.com/han811/tensorflow

profile
han811

0개의 댓글