반응형

Keras 모델 학습

Keras는 딥러닝 모델을 쉽게 구축하고 훈련할 수 있도록 설계된 오픈 소스 딥러닝 라이브러리입니다. François Chollet이 개발한 Keras는 사용자 친화적인 API를 제공하여 TensorFlow, Theano, CNTK 등의 백엔드 엔진에서 실행할 수 있습니다. 하지만 2019년 9월 기준으로 TensorFlow 2.0부터는 Keras가 TensorFlow의 공식 고수준 API로 통합되어 TensorFlow의 일부가 되었습니다.

 

< Keras 특징 >

사용자 친화적인 API: Keras는 직관적이고 간결한 API를 제공하여 신경망 모델을 쉽게 설계할 수 있도록 도와줍니다. 따라서 딥러닝 경험이 적은 사용자도 비교적 쉽게 모델을 구축하고 수정할 수 있습니다.
모듈화: Keras는 레이어, 손실 함수, 최적화 알고리즘 등을 모듈화하여 개별 구성 요소들을 조합하여 모델을 구축할 수 있도록 합니다. 이를 통해 모델의 재사용성이 높아집니다.
다양한 백엔드 지원: Keras는 다양한 딥러닝 백엔드 엔진을 지원합니다. 초기에는 Theano와 TensorFlow를 지원했으며, 현재는 TensorFlow가 공식 백엔드로 사용되고 있습니다.
모듈화된 구조: Keras는 레이어로 구성된 모델을 생성하는 함수형 API와 순차적으로 레이어를 쌓는 Sequential API를 제공합니다. 이를 통해 간단한 모델에서부터 복잡한 모델까지 다양한 구조의 신경망을 쉽게 만들 수 있습니다.
커뮤니티와 생태계: Keras는 활발한 커뮤니티와 풍부한 생태계를 갖추고 있습니다. 이로 인해 다양한 확장 기능, 사전 훈련된 모델, 유틸리티 등을 쉽게 활용할 수 있습니다.
분산 훈련 및 모델 배포: Keras는 TensorFlow를 백엔드로 사용하기 때문에 TensorFlow의 기능을 활용하여 분산 훈련과 모델 배포를 지원합니다.
가벼운 라이브러리: Keras는 간단하고 가벼운 딥러닝 라이브러리이기 때문에 처음 딥러닝을 배우는 데 적합하며, 초보자와 중급 사용자 모두에게 추천됩니다.
Keras는 이러한 특징들로 인해 딥러닝 모델 개발에 있어서 많은 사용자들에게 인기가 있으며, 다양한 응용 분야에서 활용되고 있습니다. TensorFlow를 기반으로 하기 때문에 TensorFlow와의 호환성이 뛰어난 것도 Keras의 장점 중 하나입니다.


//
//  MNIST - KERAS
//
//  Created by netcanis on 2023/07/20.
//

import numpy as np
import tensorflow as tf
import dataset_loader
import model_tester

from keras.models import load_model


# Load MNIST data
training_images, training_labels, test_images, test_labels = dataset_loader.load_dataset("data/MNIST")

# Reshape the data
# 배열의 차원을 변경하여 크기를 자동으로 변경한다. (-1은 해당 차원의 크기를 자동으로 조정하라는 뜻)
training_images = training_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)

# Print the image shapes
# reshape - Training Images shape: (60000, 28, 28, 1)
# reshape - Test Images shape: (10000, 28, 28, 1)
print("reshape - Training Images shape:", training_images.shape)
print("reshape - Test Images shape:", test_images.shape)

# Normalize the pixel values
training_images = training_images / 255.0
test_images = test_images / 255.0

# Assign images and labels to x_train, y_train, x_test, y_test
x_train, y_train = training_images, training_labels
x_test, y_test = test_images, test_labels




#
# Keras model 파일(keras) 저장
#

# TensorFlow Keras model
keras_model = tf.keras.Sequential([
    tf.keras.layers.Reshape(target_shape=(28, 28) + (1,), input_shape=(28, 28)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax') # 0~9 총 10개 클래스
])

# Train the model
keras_model.compile(optimizer='adam', 
                    loss='sparse_categorical_crossentropy', 
                    metrics=['accuracy'])
keras_model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

# Save the Keras model
keras_model.save('keras_mnist_model.h5')

print("Complete Save the Keras model.")




#
# TEST
#

model_file = "keras_mnist_model.h5"
model_tester.test_model("data/MNIST", model_file)

# Error rate: 2.26%

 

2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

Q-learning  (0) 2023.08.28
MNIST - TensorFlowLite  (0) 2023.07.19
MNIST - RandomForestClassifier  (0) 2023.07.19
MINST - SVC(Support Vector Classifier)  (0) 2023.07.19
MNIST 모델 테스터  (0) 2023.07.19
블로그 이미지

SKY STORY

,