Keras 는 Layer(층)을 조합하여 Model을 만들며, 층의 그래프 입니다.

가장 기본적인 모델은 Keras.Sequential Model 입니다.

 

 

Keras Function API  Sequential 모델 설명

 

from keras import Sequential
from keras.layers import Dense, Activation

# for a single-input model with 2 classes

model = Sequential()

▣  Layer 층의 기본적인 모델인 Sequential 을 선언합니다.

model.add(Dense(32, activation='relu'))

▣  32개의 유닛을 가진 연결층을 모델에 추가합니다.

model.add(Dense(32, activation='relu'))

▣  또하나의 연결층을 모델에 추가 합니다.
model.add(Dense(1, activation='sigmoid'))

▣  1개의 출력 유닛을 가진 softmax 층을 추가합니다.

 

Keras.layers 의 매개변수

  • activation :  Layers의 활성화 함수를 설정 합니다. 기본값은 활성화 함수를 적용하지 않습니다.  'relu' 나 'sigmoid' 등 기본으로 제공되는 함수를 쓰거나 호출 가능한 객체를 지정 할 수 있습니다.
  • kernel_initializerbias_initializer : Layer 의 weight kernel 과 bias 를 초기화 하는 방법입니다.   내장 함수나 호출 가능한 객체를 지정할 수 있으며, 기본값으로 glorot_uniform 초기화 입니다
  • kernel_regularizerbias_reqularizer : Layer의 weight Kernel 과 bias 에 적용할 규제방법을 지정   할 수 있습니다. 기본값은 규제를 지정하지 않습니다.

model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
              loss
='categorical_crossentropy',
              metrics
=['accuracy'])

모델을 구성한후 compile 메서드를 호출하여 학습과정을 설정합니다.

 Keras.model.compile 의 매개변수

  • optimizer : tf.keras.optimizers.Adam 이나 tf.keras.optimizers.SGD 의 객체를 전달 합니다.  기본 매개변수를 사용할 경우 'adam' 이나 'sgd' 의 문자열로 지정할 수 있습니다.
  • loss : 최적화 과정에서 최소화될 loss function 을 설정 합니다. categorical_crossentropy, binary_crossentropy  자주 사용되며, loss function 의 함수 이름을 지정하거나 호출 가능한 객체를 전달할 수 있습니다.
  • mertics : 훈련을 모니터링 하기위한 객체입니다.

# Numpy random Data 로 훈련하는 예제

import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

val_data = np.random.random((100, 100))
val_labels = np.random.random((100, 1))

model.fit(data, labels, epochs=10, batch_size=32, validation_data=(val_data, val_labels))

fit 메서드를 호출하여 훈련데이터를 학습합니다.

 Keras.model.fit 의 매개변수

  • epochs : 학습훈련은 에포크(epochs) 로 구성되며, 학습반복 횟수를 의미합니다.
  • batch_size :  정수값으로 배치의 크기를 지정하면 모델은 데이터를 작은 배치로 나누어 훈련학습을 합니다.
  • validation_data : prototype 의 모델을 만들때 validation data로 성능 검증을 합니다. input 과 Label 의 tuple을 이   매개변수로 전달하면 에포크가 끝날때 마다  inference mode 에서 데이터의 손실과 측정결과를 출력합니다.

model.evaluate(val_data, val_labels, batch_size=32)


result = model.predict(data, batch_size=32)

keras.Model.evaluatekera.Model.predict 메서드로 inference mode에서 손실과 지표를 평가합니다.

Keras의 Function API는 레이어 그래프를 작성하기위한 도구로 딥러닝의 일반적인 계층의

DAG(Directrd Acyclic Graph)라는 아이디어를 기반으로 하는 모델을 생성하는 예제입니다.

비선형 모델이나 공유 layer가 있는 모델 및 여러 입력이나 출력이 있는 모델에 사용됩니다.

 

3층 구조의 입출력이 있는 모델 예제 입니다.

INPUT    (input : 784-dimensional vectors)

1Layer    [Dense (64 units, relu activation)]

2Layer    [Dense (64 units, relu activation)]

3Layer    [Dense (64 units, softmax activarion]

OUTPUT (output: probability districbution over 10 classes)

 

텐서플로우 데이터세트 목록 보기

 

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Data Type 784 Vector
inputs = keras.Input(shape=(784,))

# 1Layer
dense = layers.Dense(64, activation='relu')
x = dense(inputs)
# 2Layer
x = layers.Dense(64, activation='relu')(x)

# 3Layer
outputs = layers.Dense(10, activation='softmax')(x)

model = keras.Model(inputs=inputs, outputs=outputs)


# model 요약
model.summary()

 

실행결과

 

Model: "model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         [(None, 784)]             0         
_________________________________________________________________
dense (Dense)                (None, 64)                50240     
_________________________________________________________________
dense_1 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_2 (Dense)              (None, 10)                650       
=================================================================
Total params: 55,050
Trainable params: 55,050
Non-trainable params: 0
_________________________________________________________________

딥러닝 모델과 같이 사용하기위해 PIL 형식의 이미지를 Numpy 배열로

변환하기 위한 img_to_array() 함수 입니다.

 

example load Image : imgtest.png

 

 

 

Keras API 로 Image 를 Numpy 배열로 변환하는 방법 예제

 

# example of loading an image with the Keras API

import tensorflow as tf
import keras
from keras.preprocessing.image import img_to_array, load_img, array_to_img

# load the image
img = load_img('imgtest.png')
print(type(img))

# Convert to numpy array
image_array = img_to_array(img)

print(image_array.dtype)
print(image_array.shape)
print(type(img))

# Convert back to image
image_pil = array_to_img(image_array)

print(type(img))

 

실행결과

 

<class 'PIL.Image.Image'>
float32
(300, 300, 3)
<class 'PIL.Image.Image'>
<class 'PIL.Image.Image'>

 

 

example load Image : tensorflow_100.png 를 PIL 이미지로 Load 하고

Load 된 이미지에 대한 세부 정보를 볼 수 있습니다.

 

 

Keras API 로 Image Load 방법 예제

 

# example of loading an image with the keras API

import tensorflow as tf
import keras
from keras.preprocessing.image import img_to_array, load_img

# load the image
img = load_img('tensorflow_100.png')

print(type(img))
print(img.format)
print(img.mode)
print(img.size)


# show load image
img.show()

 

실행결과

 

<class 'PIL.Image.Image'>
None
RGB
(117, 117)

 

+ Recent posts