컴공과컴맹효묘의블로그

TensorFlowCore 기초 : 이미지 분류하기 본문

컴퓨터/Tensor Flow

TensorFlowCore 기초 : 이미지 분류하기

효묘 2020. 4. 4. 20:05
반응형

tf 버전 : 2.0.0

import

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow import keras

https://www.tensorflow.org/tutorials/keras/classification 이거 따라침

위 tutorial은 60,000개의 이미지 train set을 학습시킨다. 목표는 10 종류의 의류를 분류하는 것.

+tensorflow 공식 사이트 튜토리얼인데 모델 구현이 너무 쉽다. 진짜 초보자 / 비전공자를 위한듯.

keras로 모델을 구현하는 방법은 3단계로 나뉨.

  1. 모델 쌓기
  2. 모델 컴파일
  3. 모델 학습

모델 쌓기

모델 쌓기는 학습 모델의 레이어 층을 쌓는 것이다.

model = keras.Sequential([
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

첫 번째 layer는 Flatten으로 28*28 이미지 데이터를 평평하게 (784)로 만들어 준다.

두 번째 layer는 활성화 함수가 relu인 node들을 784에서 128로 줄여준다

세 번째 layer는 활성화 함수가 softmax인 node들을 128에서 10으로 줄여준다.

모델 컴파일

학습전 세팅이다.

optimizer : loss를 바탕으로 모델 업데이트 방법 결정

loss : 비용함수.

metrics : y_true와 y_pred의 모니터링.

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

모델 학습

학습하기

epochs는 반복 횟수

참고로 train_images는 numpy.ndarray 이고 (60000, 28, 28)크기이다.

model.fit(train_images, train_labels, epochs=5)

evaluate

모델이 얼마나 정확한 답을 하는지 알아보자.

test_loss, test_acc = model.evaluate(train_images, train_labels, verbose=2)

FullCode

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow import keras

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels),(test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

train_images = train_images/255.0
test_images = test_images/255.0

model = keras.Sequential([
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(train_images, train_labels, epochs=5)

test_loss, test_acc = model.evaluate(train_images, train_labels, verbose=2)


print('\n테스트 정확도 :',test_acc)
print('loss함수 최적값 :',test_loss)
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

다음으로 읽어볼 것. https://www.tensorflow.org/tutorials/customization/basics

반응형
Comments