import tensorflow as tf
import keras
import sys
### 라이브러리 확인
import numpy as np # 선형대수 관련(배열 생성 관련)
import matplotlib # 시각화
import matplotlib.pyplot as np
print(tf.__version__)
print(keras.__version__)
print(sys.version)
2.15.0 2.15.0 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]
가. 데이터 셋 준비 및 데이터 형태 맞추기
나. 모델 구축
다. 모델 학습과정 설정하기( 학습에 대한 설정 - compile() )
라. 모델 학습( 모델을 훈련셋(train)으로 학습 - fit() 함수 )
십진수 숫자를 0,1로 이루어진 것으로 변환(스칼라를 1차벡터로 변환)
데이터 셋(손글씨)
모델 만들기
딥러닝 층 구성
# 사용할 패키지 불러오기
from keras.utils import to_categorical
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Activation
# 데이터셋 불러오기 (학습, 테스트)
(X_train, y_train), (X_test, y_test) = mnist.load_data()
import matplotlib.pyplot as plt
figure,axes = plt.subplots(nrows=3, ncols=5) # 3행 5열의 구조
figure.set_size_inches(18,12) # 전체 크기
plt.gray()
print("label={}".format(y_train[0:15])) # x데이터 0~14개 가져오기
col = 0
for row in range(0,3):
col = row * 5
axes[row][0].imshow(X_train[col]) # 0,5,10의 값을 갖는 위치 값 이미지 표시
axes[row][1].imshow(X_train[col+1])# 1,6,11의 값을 갖는 위치 값 이미지 표시
axes[row][2].imshow(X_train[col+2])# 2,7,12의 값을 갖는 위치 값 이미지 표시
axes[row][3].imshow(X_train[col+3])# 3,8,13의 값을 갖는 위치 값 이미지 표시
axes[row][4].imshow(X_train[col+4])# 4,9,114의 값을 갖는 위치 값 이미지 표시
label=[5 0 4 1 9 2 1 3 1 4 3 5 3 6 1]
fig, axes = plt.subplots(3, 5, figsize=(18,12),
subplot_kw= {'xticks':(), 'yticks':() })
print("label={}".format(y_train[0:15])) # x데이터 0~14개 가져오기
for image, ax in zip( X_train, axes.ravel() ):
ax.imshow(image) # 이미지 표시
label=[5 0 4 1 9 2 1 3 1 4 3 5 3 6 1]
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 2. 모델 구성하기
model = Sequential()
model.add(Dense(units=64, input_dim=28*28, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
# 3. 모델 학습과정 설정하기
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
# 4. 모델 학습시키기
# validation_data : 모델을 학습할때는 기본 데이터를 이용하고,
# 평가시에 사용할 데이터를 지정
hist = model.fit(X_train, y_train,
validation_data=(X_test, y_test),
epochs=10, batch_size=32)
Epoch 1/10 1875/1875 [==============================] - 6s 3ms/step - loss: 5.7090 - accuracy: 0.1385 - val_loss: 2.1920 - val_accuracy: 0.1624 Epoch 2/10 1875/1875 [==============================] - 4s 2ms/step - loss: 2.2406 - accuracy: 0.1491 - val_loss: 2.1901 - val_accuracy: 0.1681 Epoch 3/10 1875/1875 [==============================] - 5s 3ms/step - loss: 2.2583 - accuracy: 0.1502 - val_loss: 2.3077 - val_accuracy: 0.1135 Epoch 4/10 1875/1875 [==============================] - 5s 2ms/step - loss: 2.2896 - accuracy: 0.1196 - val_loss: 2.2501 - val_accuracy: 0.1352 Epoch 5/10 1875/1875 [==============================] - 4s 2ms/step - loss: 2.2406 - accuracy: 0.1442 - val_loss: 2.1748 - val_accuracy: 0.1662 Epoch 6/10 1875/1875 [==============================] - 6s 3ms/step - loss: 2.2110 - accuracy: 0.1646 - val_loss: 2.1609 - val_accuracy: 0.1744 Epoch 7/10 1875/1875 [==============================] - 4s 2ms/step - loss: 2.2574 - accuracy: 0.1382 - val_loss: 2.1838 - val_accuracy: 0.1631 Epoch 8/10 1875/1875 [==============================] - 4s 2ms/step - loss: 2.1798 - accuracy: 0.1675 - val_loss: 2.1802 - val_accuracy: 0.1614 Epoch 9/10 1875/1875 [==============================] - 6s 3ms/step - loss: 2.1996 - accuracy: 0.1641 - val_loss: 2.2824 - val_accuracy: 0.1315 Epoch 10/10 1875/1875 [==============================] - 4s 2ms/step - loss: 2.2158 - accuracy: 0.1592 - val_loss: 2.1591 - val_accuracy: 0.1730
# 5. 학습과정 살펴보기
print('## training loss and acc ##')
print(hist.history['loss']) # 'val_loss' : 평가셋 손실값
print(hist.history['accuracy']) # 'val_acc' : 평가셋 정확도
## training loss and acc ## [5.708974838256836, 2.240565061569214, 2.258289337158203, 2.289607524871826, 2.2405731678009033, 2.2109503746032715, 2.2573599815368652, 2.179774045944214, 2.199599504470825, 2.215761661529541] [0.13854999840259552, 0.14906667172908783, 0.1501999944448471, 0.11964999884366989, 0.14418333768844604, 0.16459999978542328, 0.1381833404302597, 0.1674666702747345, 0.16410000622272491, 0.15921667218208313]
plt.figure(figsize=(10, 6))
plt.subplot(1,2,1)
plt.plot(hist.history['loss'], label="loss")
plt.legend()
plt.subplot(1,2,2)
plt.plot(hist.history['accuracy'], label="accuracy")
plt.legend()
<matplotlib.legend.Legend at 0x7fc5d9e78040>
loss_and_metrics = model.evaluate(X_test, y_test, batch_size=32)
print('## evaluation loss and_metrics ##')
print(loss_and_metrics)
313/313 [==============================] - 1s 2ms/step - loss: 2.1591 - accuracy: 0.1730 ## evaluation loss and_metrics ## [2.1590678691864014, 0.17299999296665192]