Artificial Intelligence/Deep Learning

[딥러닝] Tensorflow로 신경구조망 모형 만들기 - Sequential API, Functional API

EunjiBest 2022. 1. 22. 01:08

[딥러닝] Tensorflow로 신경구조망 만들기 - 시퀀스 API, 함수형 API

 

 

Tensorflow(텐서플로우) 2.0

Tensorflow는 파이썬을 이용해서 딥러닝 학습에 사용하는 프레임워크이다.

특히 신경망을 기반으로 하는 관련 연산 처리를 할 수 있어 사용을 한다.

 

Tensorflow를 이용해서 신경망을 만두는 방법은 두가지가 있다.

 

 

1. 시퀀스 API

시퀀스 API는 직관적이고 편리하지만 복잡한 신경망을 구현할 수 없다.

처음 사용하는 사람들은 시퀀스 API가 익숙해지고 함수 API를 사용하는 것이 배우기 쉬울것이다.

 

시퀀스 API는 텐서플로에서 제공하는 Sequential()을 통해서 딥러닝 구조의 층을 쌓을 수 있다.

Sequential()을 먼저 모형을 선언 하고 model.add() 함수로 하나씩 층을 쌓을 수 있다.

 

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential()
model.add(Dense(100, activation='relu',
                input_shape = (32,32,1)))
model.add(Dense(50, activation = 'relu'))
model.add(Dense(5, activation = 'softmax'))
model.summary()

위 코드는 시퀀스 API방법을 사용해서 만든 Sequential()딥러닝 모형이다.

모형을 생성하고 model.add()메소드를 통해서 층을 쌓은 모습이다.

model.summary()를 하면 모형의 정보를 아래 처럼이쁘게 볼 수 있다.

Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense_1 (Dense)             (None, 32, 32, 100)       200       
                                                                 
 dense_2 (Dense)             (None, 32, 32, 50)        5050      
                                                                 
 dense_3 (Dense)             (None, 32, 32, 5)         255       
                                                                 
=================================================================
Total params: 5,505
Trainable params: 5,505
Non-trainable params: 0
_________________________________________________________________

 

 

2. 함수형 API

이름처름 각 층을 함수로 정의한다.

시퀀스 API와 다르게 다중 입력과 다중 출력을 가지는 모델을 만들 수 있다.

 

위 시퀀스 API와 동일한 모형 구조를 함수형 API로 구현해봤다.

from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model

input_layer = Input(shape = (32,32,1))
x = Dense(units=100, activation = 'relu')(input_layer)
x = Dense(units=50, activation = 'relu')(x)
output_layer = Dense(units=5, activation='softmax')(x)
model2 = Model(input_layer, output_layer)
model2.summary()

Dense함수를 사용할 때에 activation도 옵션으로 사용할 수있다. 임의로 relu함수를 넣었다.

역시 model2.summary()로 모형을 확인할 수 있다.

Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_3 (InputLayer)        [(None, 32, 32, 1)]       0         
                                                                 
 dense_6 (Dense)             (None, 32, 32, 100)       200       
                                                                 
 dense_7 (Dense)             (None, 32, 32, 50)        5050      
                                                                 
 dense_8 (Dense)             (None, 32, 32, 5)         255       
                                                                 
=================================================================
Total params: 5,505
Trainable params: 5,505
Non-trainable params: 0
_________________________________________________________________

 

x = Dense(units=50, activation = 'relu')(x)

위 코드는 은닉층과 activation을 분리해서 아래와 같이 사용할 수 있다.

x = Dense(units = 100)(x)
x = Activation('relu')(x)

편한대로 사용하면 되겠다.

 

 

 

모형 저장, 불러오기

 

model.save('cnn_model.h5')

모형저장은 save메소드를 사용해서 간단하게 저장할 수 있다. 

모형은 대용량 데이터를 저장하기 위해 .h5파일로 저장을 한다.

 

from tensorflow.keras.models import load_model
cnn_model2 = load_model('cnn_model.h5')

저장한 모형을 불러오는 방법이다.

load_model함수를 불러와서 모형을 다시 학습시키지 않고 바로 사용할 수 있다.

 

 

 

 

 

 

반응형