이번에는 Keras를 사용해서 MNIST 문자인식 구현했다.
확실히 PyTorch에 비해 구현하기가 간단하고 편했다.
구조
구조는 PyTorch와 같다.
2개의 Convolution layer와 2개의 FC레이어로 구성했다.
각 layer의 중간에 오버피팅을 줄이고 연산량을 감소시키기 위해 Max pooling 하였고,
Convolution layer의 끝에는 Dropout을 적용했다.
소스코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
!pip install -q tensorflow-gpu==2.0.0-rc1
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# 픽셀 값을 0~1 사이로 정규화합니다.
train_images, test_images = train_images / 255.0, test_images / 255.0
model = models.Sequential()
model.add(layers.Conv2D(10, (5, 5), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(20, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(100, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) |
cs |
PyTorch에 비해서 코드가 훨씬 간단하다.
Convolution layer를 구성하는 부분이나, FC layer를 구성하는 부분도 한줄이면 끝난다.
결과
'개발 > 파이썬' 카테고리의 다른 글
[Python] YOLOv5 Custom dataset 으로 학습하기 (26) | 2020.09.17 |
---|---|
[Python] OpenCV로 이미지 배경 제거하기 (0) | 2020.09.16 |
[Python] 파이토치(PyTorch) 학습한 모델 저장 & 불러오기 (0) | 2020.09.08 |
[Python] MNIST 예제를 통한 Keras, PyTorch 비교 (2) | 2020.08.25 |
[Python] 파이토치(PyTorch)를 사용한 MNIST 문자인식 구현 예제 (0) | 2020.08.25 |