愛林

[Python/DL] 딥 러닝 (Deep Learning) - Keras 본문

Data Science/Deep Learninng

[Python/DL] 딥 러닝 (Deep Learning) - Keras

愛林 2023. 1. 12. 16:28
반응형

Deep Learning - Keras

https://keras.io/

https://keras.io/

 

Keras: the Python deep learning API

State-of-the-art research. Keras is used by CERN, NASA, NIH, and many more scientific organizations around the world (and yes, Keras is used at the LHC). Keras has the low-level flexibility to implement arbitrary research ideas while offering optional high

keras.io

 

Python 에서 Deep Learning 을 공부할 때 이 라이브러리가 빠질 수는 없다고 생각한다.

Keras는 딥러닝을 사용자가 보다 더 편하게 구현할 수 있도록 만들어주는 인터페이스이다.

Keras 는 그리스어로 뿔(κέρας)을 의미한다.      뿔 모양 로고가 있었다면 좀 더 로고가 멋있었을 것 같은데

케라스에는 자연어 처리 뿐만 아니라 여러 방면에서 딥러닝으로 구현할 수 있는 도구들을 지원한다.

CPU , GPU에서도 매끄럽게 가동된다.

여러가지 딥러닝 Pre-trained model 들도 지원한다.

 

원래는 단일 라이브러리로 import keras 를 해서 지원했으나,

구글에게 잡아먹힌 관계로 import tensorflow.keras 로 라이브러리를 불러온다.

 

케라스는 MIT 라이선스를 따르기 때문에 상업적 프로젝트에도 자유롭게 사용이 가능하다.

Python 2.7에서 Python 3.6까지 호환한다.

자세한 것은 위의 케라스 공식 사이트를 참고하길 바란다.

 

딥러닝 프레임워크에 대한 구굴의 웹 검색 Trend

 

Keras 를 사용하면 이미지 러닝부터 NLP까지 다양하게 학습시킬 수 있다.

NLP 에서 토큰화를 할 수 있도록 Tokenizer() 를 지원하고 , 패딩을 위한 pad_ssequence() 함수를 지원한다.

 

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

tokenizer = Tokenizer()
train_text = "The earth is an awesome place to live"

# 단어 집합 생성
tokenizer.fit_on_texts([train_text])

# 정수 인코딩
sub_text = "The earth is an great place live"
sequences = tokenizer.texts_to_sequences([sub_text])[0]

print("정수인코딩 : ", sequences)
print("단어 집합 : ", tokenizer.word_index) # great 은 train text에 없으므로 출력되지 않음
정수인코딩 :  [1, 2, 3, 4, 6, 8]
단어 집합 :  {'the': 1, 'earth': 2, 'is': 3, 'an': 4, 'awesome': 5, 'place': 6, 'to': 7, 'live': 8}

great 은 학습되지 않았기 때문에 인코딩결과에 나오지 않았다. (5가 없음)

 

pad_sequences([[1,2,3],[3,4,5,6],[7,8]], maxlen = 3, padding = 'pre')
array([[1, 2, 3],
       [4, 5, 6],
       [0, 7, 8]])

 

첫 번째 인자는 패딩시킬 데이터이다.

maxlen 은 정규화할 길이이다. pad_sequences 는 maxlen 보다 길이가 긴 샘플은 값을 일부 자르고,

정해준 길이보다 길이가 짧은 sample 들은 0으로 채운다.

padding 파라미터는 'pre' 를 선택했을 시에는 앞에 0을 채워서 패딩을 진행하고,

'post' 를 선택하면 뒤에 0을 채운다.

 

keras 를 사용하면 쉽게 Modeling 또한 가능하다.

Sequential() 을 사용하면 층을 쉽게 구성할 수 있다.

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

model = Sequential()
model.add(...) # 층 추가
model.add(...) # 층 추가
model.add(...) # 층 추가

model.add 를 사용해서 층을 추가할 수 있다.

Embedding() 을 통해 임베딩 층(Embedding Layer) 을 추가할 수 있다.

model = Sequential()
model.add(Embedding(vocab_size, output_dim, input_length))

전결합층 (Dense Layer) 또한 쉽게 추가가 가능하다.

model = Sequential()
model.add(Dense(1, input_dim=3, activation='relu'))

위 코드는 위 사진과 같은 모델을 구성한 것이다.

Dense 의 맨 앞 인자는 출력할 뉴런의 수, input_dim 의 입력할 뉴런의 수이다.

input_dim 은 보통 맨 앞 입력뉴런에서 사용된다.

activation 은 활성화 함수인데, linear, sigmoid, softmax, relu 등을 지원한다.

 

은닉층을 하나 더 추가하여 모델을 만들어볼 수 있다.

model = Sequential()
model.add(Dense(8, input_dim=4, activation='relu'))
model.add(Dense(1, activation='sigmoid')) # 출력층

add 로 손쉽게 추가가 가능하다.

위의 코드는 아래와 같은 모델을 만드는 코드이다.

이 외에도 LSTM, GRU, Convolution 2D, BatchNormalization 등 다양한 층을 만들 수 있다.

summary() 를 사용하여 모델의 정보와 구조를 살펴볼 수 있다.

 

model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 8)                 40        
                                                                 
 dense_1 (Dense)             (None, 1)                 9         
                                                                 
=================================================================
Total params: 49
Trainable params: 49
Non-trainable params: 0
_________________________________________________________________

 

compile() 을 사용하면 모델을 머신이 이해할 수 있도록 compile 시킬 수 있다.

Loss function, Optimizer , metrics 파라미터를 넣을 수 있다.

 

from tensorflow.keras.layers import SimpleRNN, Embedding, Dense
from tensorflow.keras.models import Sequential

vocab_size = 10000
embedding_dim = 32
hidden_units = 32

model = Sequential()
model.add(Embedding(vocab_size, embedding_dim))
model.add(SimpleRNN(hidden_units))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])

대표적인 Loss function 들과 activation funciton 의 조합은 다음과 같다.

 

 

fit() 으로 모델을 학습시킬 수 있다.

model.fit(X_train, y_train, epochs=10, batch_size=32)

Epoch는 에폭 수를 선정하는 것이고, batch_size 는 배치 크기이다. 디폴트 값은 32이며, 

미니 배치 경사 하강법을 사용하고 싶지 않은 경우에는 Batch_size = None 을 사용한다.

 

이 외에도 validation_data, validation_split 등을 사용할 수 있다.

model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0, validation_data(X_val, y_val))

validation data 를 사용할 때는 각 Epoch 마다 검증 데이터의 정확도나 오차를 함께 출력한다. 이 정확도는 훈련이 

잘 되고 있는 지만을 보여준다.

실제로 모델이 검증 데이터를  학습하지는 않는다.

 

validation split 을 사용하면 훈련 데이터 중 얼만큼의 비율을 검증 데이터로 사용할 지 선정할 수 있다.

# 훈련 데이터의 20%를 검증 데이터로 사용.
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0, validation_split=0.2))

verbose 는 학습 중에 출력되는 문구를 설정한다.

  • 0 : 아무것도 출력하지 않는다
  • 1 : 훈련의 진행도를 보여주는 진행 막대를 보여준다.
  • 2 : 미니 배치마다 손실정보를 출력한다.
# verbose = 1일 경우.
Epoch 88/100
7/7 [==============================] - 0s 143us/step - loss: 0.1029 - acc: 1.0000
# verbose = 2일 경우.
Epoch 88/100
 - 0s - loss: 0.1475 - acc: 1.0000

 

evaluatepredict 또한 사용이 가능하다.

evaluate 를 사용하여 모델에 대한 정확도를 평가할 수 있다.

predict 으로 예측을 진행할 수 있다.

# 평가
model.evaluate(X_test, y_test, batch_size=32)
# 예측
model.predict(X_input, batch_size=32)

 

모델의 성능 향상을 위한 DropOut 이나 정규화 또한 지원한다.

model = Sequential()
model.add(Dense(128, input_shape=(784,), activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(10, activation='softmax'))

 

모델의 결과를 저장하면 plot 을 그릴 수도 있다.

hist = model.fit(feature_train_df, train_labels, epochs=10, validation_split=0.2, verbose=1)
pd.DataFrame(hist.history)[['acc', 'val_acc']].plot()

 

 

 

 

API


Keras 딥 러닝 모델 설계 방법으로는 Sequential, Functional API, Subclassing API 가 있다.

 

 

1) Sequential API

 

sequential 모델은 모델을 선형으로 쌓은 것이다. Keras 에서는 아주 간단한 방법으로 Sequential API 를 구현 가능하다.

위에서 살펴본 모델들이 모두 Sequential API 를 사용한 것이다.

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

model = Sequential()
model.add(Dense(3, input_dim=4, activation='softmax'))

단 몇 줄로 간단하게 신경망을 구성한다.

그리고 매우 직관적이라는 것이 장점이다. 그러나 단순히 층을 쌓기만 하는 것이기 때문에

더 복잡한 신경망은 구현할 수 없다. 따라서 초심자에게는 매우 적절한 API이지만 더 고도화되고 까다로운

모델을 만들기 위해서는 Functional API 로 넘어가는 것이 좋다.

 

 

2) Functional API

 

Functional API 는 말 그대로 함수형으로 모델을 만드는 것이다.

각 층을 일종의 함수(Funciton) 으로서 정의한다.

그리고 각 함수를 조합하기 위한 연산자들을 이용하여 신경망을 설계한다. 

Functional API 를 조금 더 알아보자.

Funcitonal API 는입력의 크기 (Shape) 을 명시한 입력층(Input Layer) 을 모델 앞단에 정의해주어야 한다.

 

먼저 FNN(Fully-connected FFNN) 을 만들어보자.

from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
inputs = Input(shape=(10,))

위의 코드는 10개의 입력을 받는 입력층(inputs)을 보여준다. 

이제 층을 더 추가해보자.

inputs = Input(shape=(10,))
hidden1 = Dense(64, activation = 'relu')(inputs)
hidden2  = Dense(64, activation = 'relu')(hidden1)
output = Dense(1, activation = 'sigmoid')(hidden2)
model = Model(inputs = inputs, outputs = output)

hidden layer 2개를더 만들고, 모델을 만들어주었다.

이를 model 에 저장하면 compile 과 fit 을 사용할 수 있다.

model.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
# model.fit(data, labels)

 

변수 이름을 바꾸어 만드는 것도 가능하다.

inputs = Input(shape=(10,))
x = Dense(8, activation="relu")(inputs)
x = Dense(4, activation="relu")(x)
x = Dense(1, activation="linear")(x)
model = Model(inputs, x)

 

Functional API 를 사용하면 다중 입력과 다중 출력을 가지는 모델도 만들 수 있다.

# 최종 완성된 다중 입력, 다중 출력 모델의 예
model = Model(inputs=[a1, a2], outputs=[b1, b2, b3])

다중 입력과 출력을 받는 모델을 설계해보자.

 

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

# 두 개의 입력층을 정의
inputA = Input(shape=(64,))
inputB = Input(shape=(128,))

# 첫번째 입력층으로부터 분기되어 진행되는 인공 신경망을 정의
x = Dense(16, activation="relu")(inputA)
x = Dense(8, activation="relu")(x)
x = Model(inputs=inputA, outputs=x)

# 두번째 입력층으로부터 분기되어 진행되는 인공 신경망을 정의
y = Dense(64, activation="relu")(inputB)
y = Dense(32, activation="relu")(y)
y = Dense(8, activation="relu")(y)
y = Model(inputs=inputB, outputs=y)

# 두개의 인공 신경망의 출력을 연결(concatenate)
result = concatenate([x.output, y.output])

z = Dense(2, activation="relu")(result)
z = Dense(1, activation="linear")(z)

model = Model(inputs=[x.input, y.input], outputs=

이 모델은 다음과 같은 모델이다.

 

 

result = Dense(128)(input)

위와 같은 코드는

 

dense = Dense(128)
result = dense(input)

이렇게 두 개로 표현도 가능하다.

 

 

참고


https://wikidocs.net/32105

 

07-08 케라스(Keras) 훑어보기

이 책에서는 딥 러닝을 쉽게 할 수 있는 파이썬 라이브러리인 케라스(Keras)를 사용합니다. 케라스는 유저가 손쉽게 딥 러닝을 구현할 수 있도록 도와주는 상위 레벨의 인터페이스…

wikidocs.net

https://tensorflow.blog/%EC%BC%80%EB%9D%BC%EC%8A%A4-%EB%94%A5%EB%9F%AC%EB%8B%9D/3-2-%EC%BC%80%EB%9D%BC%EC%8A%A4-%EC%86%8C%EA%B0%9C/

 

3.2 케라스 소개

3. 신경망 시작하기 | 목차 | 3.3 딥러닝 컴퓨터 셋팅   이 책에서는 코드 예제를 위해 케라스( 사용합니다. 케라스는 거의 모든 종류의 딥러닝 모델을 간편하게 만들고 훈련시킬 수 있는 파이썬

tensorflow.blog

 

Comments