keras는 오픈소스 신경망 라이브러리다. 

https://ko.wikipedia.org/wiki/%EC%BC%80%EB%9D%BC%EC%8A%A4

 

케라스 - 위키백과, 우리 모두의 백과사전

 

ko.wikipedia.org

tensorflow의 버전이 달라 연동이 안 되는 점을 조정해준다고 한다. 

%tensorflow_version 2.x

#구성 바뀌어도 keras가 조정해줌
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

print(train_images.shape)
print(test_images.shape)

keras의 내장된 데이터를 train_images, train_labels와 같이 불러들인다 

 

MNIST데이터는 특성을 표현하는 부분을 2차원으로 구성되어 있다. 

print(test_images[1])

-> 줄이 다음 칸으로 밀려 정확한 확인이 어려움

 

데이터 타입은 넘파이 배열임

import numpy as np
np.set_printoptions(linewidth=np.inf )
  • 한 줄에 출력될 문자의 최대수를 늘린다. 

 

  • 두 개의 차원을 이용하여 숫자 '2' 표현
  • 각 셀의 숫자는 색상 값.
  • 숫자로 대상을 인식한다. 
import matplotlib.pyplot as plt
plt.imshow(test_images[1])

 

Layer 쌓기

from tensorflow.keras import models
from tensorflow.keras import layers
model = models.Sequential() # 모델 초기화 ( 새로운 모델을 만들 준비)

# 은닉층 설정
# 처음에는 입력 shape을 설정한다. 3차원 데이터를 2차원으로 변형할 것이다. input_shape=(특성의 수, 샘플의 수)
# 단, 샘플의 개수는 몇 개가 올지 알 수 없으므로 비워둬야 한다

model.add(layers.Dense(256, activation='relu', input_shape=(28*28,)))


# 출력층 설정. 숫자의 종류가 10개이므로, 10개의 유닛을 갖는 출력층을 설정한다
# 10개 각각에 대한 확률정보 출력. Softmax 층은 확률 점수를 출력한다
model.add(layers.Dense(10, activation='softmax'))
  • 완젼 연결 층 - Dense 층 (가장 기본이 되는 층)
    • 다 연결하는거 
  • 은닉층에 들어가는 노드의 개수 : 256
  • 첫번째 은닉층 만들 때만 input_shape설정함.
    • 3차원 데이터를 2차원으로 변형할 것. 
  • activation : 활성화 함수를 설정함
    • linear
    • relu
    • sigmoid
    • softmax
  • 출력층 설정할 때, 숫자의 종류가 10개 이므로, 10은 마음대로 조절 불가능 하다. 

 

컴파일 모델

model.compile(loss='categorical_crossentropy', optimizer='rmsprop',metrics=['accuracy'])
print(test_images[1,])
  • loss : 훈련데이터에서 신경망의 성능을 측정하는 손실 함수
  • optimizer : 입력된 데이터와 손실 함수를 기반으로 가중치를 업데이트하는 방법
  • metrics : 훈련과 테스트 과정을 모니터링할 지표 'acc'라고 쓴다. 

 

데이터 변환

train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32')/255
# reshape 함수를 이용해 데이터를 (60000, 784) 크기로 변환하고,
# 각 값을 255로 나누되, type을 소수점을 받는 float32 형으로 맞춤

전처리 후

np.set_printoptions(linewidth=310)
print(test_images[1])

 

 

종속변수를 범주형으로 변환

from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

 

데이터 학습

#학습
model.fit(train_images, train_labels, epochs=5, batch_size=128)

# 예측
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('test_acc:', test_acc)

313/313 [==============================] - 1s 2ms/step - loss: 0.0722 - accuracy: 0.9801
test_acc: 0.9800999760627747

 

 

+ Recent posts