인공지능

Tensorflow 연습 - 숫자 인식

날아가는기억잡기 2021. 8. 29. 21:41
# 순차적인 신경망을 구성할 때 사용할 수 있는 함수
from tensorflow.keras.models import Sequential
# 레이어 도구 중 Dense(전결합층, 각 층이 바로 앞의 층과 연결되어 있는 것)과 Activation(활성화 함수)를 가져옴
from tensorflow.keras.layers import Dense, Activation
# 다중 분류를 하기 위한 원-핫 인코딩을 구현할 수 있는 함수
from tensorflow.keras.utils import to_categorical
# 딥러닝 모델을 연습할 수 있는 데이터셋
from tensorflow.keras.datasets import mnist
# 수학 계산 라이브러리
import numpy as np
# 그래프 라이브러리
import matplotlib.pyplot as plt


# mnist data는 훈련 데이터와 검증 데이터로 이루어져 있다.
# x_train: 학습할 대상, y_train: 학습 대상의 정답
# y_test: 검증 데이터, y_test: 검증의 정답
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print("x_train shape", x_train.shape) # x_train shape (60000, 28, 28)
print("y_train shape", y_train.shape) # y_train shape (60000,)
print("x_test shape", x_test.shape)   # x_test shape (10000, 28, 28)
print("y_test shape", y_test.shape)   # y_test shape (10000,)


# 데이터를 일렬로 형태 변경
X_train = x_train.reshape(60000, 784)
X_test = x_test.reshape(10000, 784)


# 데이터 정규화, 데이터를 0~1 사이의 값으로 변경하기 이해 실수로 변경
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print("X Training matrix shape", X_train.shape) # X Training matrix shape (60000, 784)
print("X Testing matrix shape", X_test.shape)   # X Testing matrix shape (10000, 28, 28)


# Y 데이터를 원-핫 인코딩해줌
# to_categorical: 수치형 데이터를 범주형 데이터로 변경해줌
Y_train = to_categorical(y_train, 10)
Y_test = to_categorical(y_test, 10)
print("Y Training matrix shape", Y_train.shape) # Y Training matrix shape (60000, 10)
print("Y Testing matrix shape", Y_test.shape)   # Y Testing matrix shape (10000, 10)


# 입력층(784), 은닉층1(512), 은닉층2(256), 출력층(10)으로 설계
# 활성화 함수: ReLU함수 사용
model = Sequential()
model.add(Dense(512, input_shape=(784,))) # 층 추가, 받는 쪽의 신호는 512개, input 층의 신호는 784개
model.add(Activation('relu')) # 활성화 함수로 ReLU 함수 사용
model.add(Dense(256)) # 층 추가, 받는 쪽의 신호는 256개
model.add(Activation('relu'))
model.add(Dense(10)) # 층 추가, 받는 쪽의 신호는 10개
model.add(Activation('softmax')) # 총 합이 1이되도록 활성화 함수 추가
model.summary() # 설계한 모델에 대한 설명 출력


# 오차 계산, 경사 하강법 사용

# 오차값을 계산하는 방법: 다중 분류 문제이므로 categorial_crossentropy 사용
# 오차를 줄이는 방법: adam이라는 방법 사용
# 학습 결과를 어떻게 확인할 지: 정답 비율을 알려줌
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# batch_size: 인공지능 모델이 한 번에 학습하는 사이즈
# epochs: 모든 데이터를 몇 번 학습시킬지
# verbose: 0~2까지로, 숫자가 커질 수록 많은 정보를 알려줌
model.fit(X_train, Y_train, batch_size=128, epochs=10, verbose=1)


# 모델 정확도 파악
score = model.evaluate(X_test, Y_test)
print('Test loss:', score[0])
print('Test accuracy:', score[1])


# 모델 학습 결과 눈으로 파악, 인공지능이 잘 구분한 그림과 잘 구분하지 않은 그림 확인
predicted_classes = np.argmax(model.predict(X_test), axis=1)   # 행(가로) 중에서 가장 큰 수를 골라줌
correct_indices = np.nonzero(predicted_classes == y_test)[0]   # 맞은 값
incorrect_indices = np.nonzero(predicted_classes != y_test)[0] # 틀린 값


# 눈으로 맞은/틀린 결과를 확인하기 위한 코드
# 틀린 결과 확인을 위해서는 correct->incorrect로 수정
plt.figure()
for i in range(9):
    plt.subplot(3, 3, i+1)
    correct = correct_indices[i]
    plt.imshow(X_test[correct].reshape(28, 28), cmap='gray')
    plt.title("Predicted{}, Class{}".format(predicted_classes[correct], y_test[correct]))
plt.tight_layout()

https://www.youtube.com/watch?v=kswXuoTAUlo&list=PLRtkynNyEsXnu5XCR_sd37GQJ3ODlE4bU&index=37 

 

'인공지능' 카테고리의 다른 글

Pytorch의 tensor란?  (0) 2021.09.08
머신러닝 알고리즘들  (0) 2021.08.31
딥러닝 기술  (0) 2021.08.29
딥러닝 체험  (0) 2021.08.29
인공 신경망의 학습 원리  (0) 2021.08.29