머신러닝/Tensorflow

Tensorflow 2.0 - Basic image classification

aiemag 2021. 3. 6. 10:23
반응형

기본 이미지 분류 예제입니다.

 

keras package의 datassets 중 fashion_mnist 이미지 data에 대해 분류를 하는 모델을 만들고 예측을 해봅니다.

 

NN 모델은 입력층 뉴런 784(28*28)개 -> 은닉층 뉴런 128개  -> 출력층 뉴런 10개가 사용되었습니다.

 

NN 모델 train 시, optimizer는 adam을, loss fuction은 sparse_categorical_crossentropy를 사용하였습니다.

 

아래 코드는 기존 Tutorial에서 필요한 부분만 작성하였습니다.

 

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import tensorflow as tf
from tensorflow import keras
 
import numpy as np
import matplotlib.pyplot as plt
 
 
# load data
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
 
 
# make model
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(2828)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])
 
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
 
# train model
model.fit(train_images, train_labels, epochs=5)
 
# validation
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('test accuracy : ', test_acc)
 
# prediction
predictions = model.predict(test_images)
pred_0 = np.argmax(predictions[0])
print('1st test data label : ', test_labels[0], ', 1st test data predicted label : ', pred_0)
 
plt.figure()
plt.subplot(211)
plt.imshow(test_images[test_labels[0]])
 
plt.subplot(212)
plt.imshow(test_images[pred_0])
 
plt.show()
cs

 

결과

 

train data의 accuracy는 0.8896, test data의 accuracy는 0.874를 보여줍니다.

test data의 첫 번째 이미지의 label은 9를 가리키고 prediction 결과도 9번째 label를 가리킵니다.

반응형

'머신러닝 > Tensorflow' 카테고리의 다른 글

Tensorflow 2.0 - Text classification by TF Hub  (0) 2021.03.08
Tensorflow 2.0 - Basic text classification  (0) 2021.03.07
Tensorflow 2.0 - Tutorial  (0) 2021.03.05