본문 바로가기

Back/Deep Learning

[Tensorflow] Image classification model maker예측하기.

tflite-model-make 설치와 모델생성.


이전 글을 통해 아주 쉽게 예측 모델을 생성해 내었습니다.

model maker의 장점은 

  • 학습 속도가 매우 빠릅니다. (물론 안에 들어간 모델이 잘만들어져서 이기도 합니다.)
  • 빠른 학습속도에 비해 정확도도 높습니다.
  • 쉽게 읽고 쓸수 있도록 지원합니다.

이전글에서 모델 학습, 저장을 다루었으니 이번글에선 예측부분을 다뤄 보겠습니다.

 

필요한 lib import

import numpy as np
import tensorflow as tf
from PIL import Image
from operator import itemgetter

 

모델을 로드합니다.

# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="C:/Users/Admin/Desktop/data_fin/apple\\model.tflite")
interpreter.allocate_tensors()

 

입력과 출력에 해당하는 텐서를 얻습니다.

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

 

이미지를 불러오고 numpy 배열로 변환 합니다. 

# Load Image for predict. transform numpy array.
path = 'C:(root)\\23295B4E530D29AD27.jpg'
load_img_rz = np.array(Image.open(path).resize((224,224)))
input_data = np.array([load_img_rz],dtype=np.float32)
input_data = input_data/255

 

모델에 이미지를 입력합니다. 주석처리된 부분은 테스트용 랜덤 배열을 생성하는 부분입니다. 

# Test the model on random input data.
#input_shape = input_details[0]['shape']
#input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

 

인터프리터를 호출합니다.

interpreter.invoke()

 

get_tensor() 함수를 통해 추론이 끝난 결과물을 가져올 수 있습니다.

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(*output_data)

 

다음과 같이 소프트 맥수 함수의 결과가 반환됩니다.

[0.08551531 0.02637902 0.02720363 0.00789375 0.02414108 0.07248129
 0.01870983 0.35287014 0.02585053 0.01274899 0.02155474 0.01043957
 0.21681911 0.01511663 0.00661603 0.02855708 0.02806745 0.01903588]

 

각 값의 위치는 label 파일 안 폴더 순서대로 정렬이 되어있습니다. 즉, 위의 결과에서 최댓값과 그 index값을 반환하면 예측결과를 얻을 수 있습니다.

각 값에 인덱싱을 해줍니다.

print_data =[]
list_print_data =[]

for index, value in enumerate(*output_data):
    list_print_data.append([index,value])
    print(index,value)
    

'''
0 0.08551531
1 0.026379019
2 0.027203625
3 0.007893749
4 0.024141079
5 0.07248129
6 0.018709825
7 0.35287014
8 0.025850533
9 0.012748987
10 0.021554736
11 0.010439571
12 0.21681911
13 0.015116628
14 0.006616034
15 0.028557079
16 0.02806745
17 0.019035883
'''

 

1,2,3 순위를 확인하기 위해 itemgetter를 이용해서 내림차순으로 정렬하였습니다. 반복문으로 확률이 높은 순서대로 출력할 수 있습니다.

print_data = sorted(list_print_data, key=itemgetter(1), reverse=True)

for rank in print_data:
    print(rank)
    
 '''
[7, 0.35287014]
[12, 0.21681911]
[0, 0.08551531]
[5, 0.07248129]
[15, 0.028557079]
[16, 0.02806745]
[2, 0.027203625]
[1, 0.026379019]
[8, 0.025850533]
[4, 0.024141079]
[10, 0.021554736]
[17, 0.019035883]
[6, 0.018709825]
[13, 0.015116628]
[9, 0.012748987]
[11, 0.010439571]
[3, 0.007893749]
[14, 0.006616034]
'''

 

가장 확률이 높은것은 8번에 있는 바이로이드 라고 합니다.

 

이미지를 확인해보면 예측이 잘되었음을 알 수 있습니다.


이하 전체 코드

import numpy as np
import tensorflow as tf
from PIL import Image
from operator import itemgetter

# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="C:/Users/Admin/Desktop/data_fin/apple\\model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Load Image for predict. transform numpy array.
path = 'C:\\Users\\Admin\\Desktop\\23295B4E530D29AD27.jpg'
load_img_rz = np.array(Image.open(path).resize((224,224)))
input_data = np.array([load_img_rz],dtype=np.float32)
input_data = input_data/255


# Test the model on random input data.
input_shape = input_details[0]['shape']
#input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(*output_data)

print_data =[]
list_print_data =[]

for index, value in enumerate(*output_data):
    list_print_data.append([index,value])
    print(index,value)

list_print_data

print_data = sorted(list_print_data, key=itemgetter(1), reverse=True)

print_data[0][0]

for rank in print_data:
    print(rank)

 

ref)

www.tensorflow.org/lite/guide/inference