-
Notifications
You must be signed in to change notification settings - Fork 1
/
CNN.py
74 lines (61 loc) · 2.29 KB
/
CNN.py
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
72
73
74
from keras.models import Sequential
from keras.layers import Dropout, Dense
from keras.layers import Flatten, Convolution2D, MaxPooling2D
import numpy as np
import matplotlib.pyplot as plt
# 넘파이 배열을 불러옴
X_train, X_test, Y_train, Y_test = np.load('E:/정보보호/image_data_10.npy', allow_pickle=True)
# 학습, 검증 데이터를 CNN에 맞도록 한차원 높여줌
X_train = np.expand_dims(X_train, 3)
X_test = np.expand_dims(X_test, 3)
# 넘파이 배열로 변환
X_train = np.array(X_train)
X_test = np.array(X_test)
Y_train = np.array(Y_train)
Y_test = np.array(Y_test)
print(X_train.shape)
print(X_test.shape)
# Convolution2D를 이용한 이미지 축소
model = Sequential()
model.add(Convolution2D(64, (3, 3), border_mode='same', activation='relu', input_shape=(64, 32, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.20))
model.add(Convolution2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.20))
model.add(Convolution2D(16, (3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.20))
# Dense층을 이용한 다층 학습
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
# 모델 구조 출력
print(model.summary())
# 모델 학습 시작 (batch_size=1000 nb_epoch=500)
model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'] )
history = model.fit(X_train, Y_train, batch_size=1000, nb_epoch=500, validation_data=(X_test, Y_test), shuffle=True, verbose=2)
# 모델을 저장
model.save('E:/정보보호/10_3.h5')
# 학습내역을 가지고 학습률과 손실률을 그래프로 출력 후 저장
plt.plot(history.history['accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.grid()
plt.savefig("accuracy.png")
plt.show()
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.grid()
plt.savefig("loss.png")
plt.show()