-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnn.qmd
71 lines (54 loc) · 2.4 KB
/
cnn.qmd
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---
title: cnn.py
engine: knitr
---
```{python}
#| eval: false
#| python.reticulate: false
import sys
import tensorflow as tf
import keras
import time
import os
from tensorflow.python.keras import layers
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
start = time.time()
img_rows = 28
img_cols = 28
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
input_shape = (img_rows, img_cols, 1)
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
x_train = x_train.astype('float32') / 255. # 데이터 정규화
x_test = x_test.astype('float32') / 255. # 데이터 정규화
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
batch_size = int(sys.argv[2])
num_classes = 10
epochs = int(sys.argv[1])
y_train = keras.utils.to_categorical(y_train, num_classes) # 학습을 위한 원핫벡터로 변경
y_test = keras.utils.to_categorical(y_test, num_classes) # 원핫벡터로 변경
model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1), padding='same', activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (2, 2), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten()) # fully connected layer
# 완전 연결계층의 문제점은 데이터의 형상이 무시된다.
# conv2d로 이미지의 특성들을 뽑아내고 pooling계층을 이용하여 차원을 감소시킨후 dense layer를 사용하여 감소된 차원의 feature map들을 input으로 하여 효율적 학습을 진행
model.add(Dense(1000, activation=sys.argv[3])) # -> Dense Layer와 같은 경우에는 가장 기본적인 층으로서 완전연결계층이다.
model.add(Dropout(0.5)) # 과대적합방지를 위해 사용
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
hist = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
end = time.time() - start
print(end)
```