rueki

Tensorflow 02. mnist dataset 알아보기 본문

Tensorflow

Tensorflow 02. mnist dataset 알아보기

륵기 2019. 12. 3. 19:27
728x90
반응형

텐서플로우에서 제공하는 숫자 이미지 mnist에 대해 알아보자

 

1.라이브러리 불러오기

import numpy as np
import matplotlib.pyplot as plt # 시각화를 위한 것
import tensorflow as tf

%matplotlib inline #주피터 노트북 안에서 바로 생성

2. 데이터 불러오기

from tensorflow.keras import datasets
mnist = datasets.mnist
(train_x, train_y),(test_x, test_y) = mnist.load_data()
train_x.shape
#(60000, 28, 28) - 60000개의 데이터, 28 by 28 이미지 데이터

3. 시각화 해보기

image = train_x[0]
image.shape
# (28, 28)

plt.imshow(image, 'gray') # gray scale 이미지로 확인하기 위해서
# gray가 없으면 칼라 이미지로 나오는 것을 볼 수 있음
plt.show()

4. 이미지  Channel에 대해 알아보자

  • [batch size, Height, Width, Channel]
  • GrayScale이면 1, RGB이면 3으로

이미지가 28 x 28인 것은 볼 수 있었다. 추가로 Channel을 위한 채널을 늘려보자.

#차원 수 늘리기
nptrain_x = np.expand_dims(train_x, -1)
# -1 = 맨뒤의 차원 늘리기, 0 = 맨 앞

new_train_x = tf.expand_dims(train_x, -1)
new_train_x.shape
#(60000, 28, 28, 1)

train_x[...,tf.newaxis].shape
#(60000, 28, 28, 1)

5. label Dataset 들여다보기

이미지가 어떤 class로 인지 되는지 알아야한다. 

train_y[0] # 첫 번째 이미지에 대한 레이블 확인해보기
# 5(필자의 경우)

컴퓨터가 이해할 수 있는 형태로 label을 변환해서 주어야하는데, 

classifiaction에서는 원-핫 인코딩을 주로 사용

케라스에서 제공하는 원-핫 인코딩을 사용해보자.

from tensorflow.keras.utils import to_categorical
to_categorical(0,10)
#10개 중에서 첫 번째 인덱스를 1로 주고 나머지 0으로 주겠다라는 의미

label = train_y[0]
label_onehot = to_categorical(label, num_classes = 10)
label_onehot

plt.title(label_onehot)
plt.imshow(train_x[0], 'gray')
plt.show()
#결과는 각자 확인
728x90
반응형

'Tensorflow' 카테고리의 다른 글

TensorFlow 01. 사용법 알아보기  (0) 2019.12.03
5. Mnist 예제  (0) 2019.07.18
4.신경망 구현 - Hidden layer 추가  (5) 2019.07.17
3. 신경망 구현  (0) 2019.07.16
2. 선형회귀 구현  (0) 2019.07.16
Comments