그동안 블로그에 게시글을 작성할 때 Python을 이용하는 글들은 전부다 Python 게시판 넣었습니다. 해당 방법을 통하여 파이썬으로 다양한 것을 할 수 있다는 것을 보여주었지만 세부적인 방법을 보여주기에 한계가 있었습니다. 그래서 인공지능에 대하여 깊게 소개하기 위해 게시판을 분리하였습니다.
Keras
우선 케라스(Keras)는 파이썬 기반으로 작성된 오픈소스 딥러닝 라이브러리입니다. 딥러닝을 하기 위해 데이터 정규화 및 레이어를 쌓는 과정등 다양한 과정이 필요합니다. 특히 머신러닝을 처음 다루는 사람들은 해당 과정들이 복잡합니다. Tensorflow 라이브러리를 이용한 설계를 조금 더 사용자에게 쉽고 친숙하게 만든 라이브러리가 Keras입니다.
추가로 본 게시글에는 Tensorflow와 비교할 뿐이지 다른 딥러닝 프레임워크도 사용할 수 있습니다.
아래 링크는 Keras의 공식 깃허브 링크입니다.
https://github.com/keras-team/keras
GitHub - keras-team/keras: Deep Learning for humans
Deep Learning for humans. Contribute to keras-team/keras development by creating an account on GitHub.
github.com
Tensorflow와 Keras 이모저모
위에서도 설명했으나 Keras는 Tensorflow를 쉽게 사용하기 위해 만들어진 라이브러리입니다.
그렇기 때문에 단 몇 줄만으로 신경망 소스 코드를 구현할 수 있습니다.
머신러닝을 이용하여 간단한 소스 코드를 제작하거나 빠르게 제작이 필요한 경우에 Keras를 이용하는 것이 좋습니다.
하지만 조금 더 디테일한 조작이 필요한 경우에는 Tensorflow를 이용하는 것이 좋습니다.
기존에 있는 기능을 넘어 사용하려면 무조건 Tensorflow를 사용하는 것이 좋습니다.
Keras 설치하기
설치는 pip를 이용하여 설치하면 쉽게 설치 할 수 있습니다.
pip install tensorflow
pip install keras
tensorflow를 베이스로 keras를 사용할려고 하므로 두줄 다 설치하도록 합니다.
간단한 Keras 예시
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.utils import to_categorical
# Fashion-MNIST 데이터 로드 및 전처리
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
# 모델 구성
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
# 모델 컴파일
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 모델 학습
model.fit(x_train, y_train, epochs=10, batch_size=64, validation_split=0.2)
# 모델 테스트
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc}")
해당 예시는 CNN으로 학습된 모델로 Fashion-MNIST 데이터를 훈련하고 모델을 테스트하는 소스코드입니다. 자세한 원리는 해당 개념을 따로 블로그에 작성하도록 하겠습니다.