머신러닝

본문 바로가기
사이트 내 전체검색


머신러닝
머신러닝

6. 텐서플로 서빙으로 모델 배포하기

페이지 정보

작성자 관리자 댓글 0건 조회 1,374회 작성일 21-01-03 16:04

본문

6. 텐서플로 서빙으로 모델 배포하기

  

$ vi train.py


# -*- coding: utf-8 -*-

import tensorflow as tf

import numpy as np


file = tf.keras.utils.get_file(

    "grace_hopper.jpg",

    "https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg")

img = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224])


x = tf.keras.preprocessing.image.img_to_array(img)

x = tf.keras.applications.mobilenet.preprocess_input(

    x[tf.newaxis,...])


#tf.keras.applications.vgg19.decode_predictions

labels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')

imagenet_labels = np.array(open(labels_path).read().splitlines())

print(labels_path)


pretrained_model = tf.keras.applications.MobileNet()

result_before_save = pretrained_model(x)

print()


decoded = imagenet_labels[np.argsort(result_before_save)[0,::-1][:5]+1]


print("저장 전 결과:\n", decoded)


tf.saved_model.save(pretrained_model, "./mobilenet/1/")


loaded = tf.saved_model.load("./mobilenet/1/")

print(list(loaded.signatures.keys()))  # ["serving_default"]


infer = loaded.signatures["serving_default"]

print(infer.structured_outputs)


labeling = infer(tf.constant(x))[pretrained_model.output_names[0]]


decoded = imagenet_labels[np.argsort(labeling)[0,::-1][:5]+1]


print("저장과 불러오기 이후의 결과:\n", decoded)


$ python3 train.py

저장 전 결과:

 ['military uniform' 'bow tie' 'suit' 'bearskin' 'pickelhaube']

저장과 불러오기 이후의 결과:
 ['military uniform' 'bow tie' 'suit' 'bearskin' 'pickelhaube']


SavedModel은 파이썬에서 사용하기에 적합하지만, 일반적으로 프로덕션 환경에서는 추론을 위한 전용 서비스를 사용합니다. 
이는 텐서플로 서빙을 사용한 SavedModel로 쉽게 구성할 수 있습니다. 

tensorflow_model_server를 노트북이나 로컬 머신에 설치하는 방법을 포함한 텐서플로 서빙에 대한 자세한 내용은 TensorFlow Serving REST 튜토리얼을 참조하십시오. 

mobilenet 모델을 배포하기 위해 모델 경로를 SavedModel 디렉토리로 설정합니다: 

[root@www hopper]# ls
mobilenet  train.py
[root@www hopper]# nohup tensorflow_model_server \
   --rest_api_port=8501 \
   --model_name=mobilenet \
   --model_base_path="./mobilenet" >server.log 2>&1
[root@www hopper]# 

이제 요청을 보냅니다. 

$ vi test.py
# -*- coding: utf-8 -*-
import json
import numpy
import requests
import tensorflow as tf

file = tf.keras.utils.get_file(
    "grace_hopper.jpg",
img = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224])

x = tf.keras.preprocessing.image.img_to_array(img)
x = tf.keras.applications.mobilenet.preprocess_input(
    x[tf.newaxis,...])


data = json.dumps({"signature_name": "serving_default",
                   "instances": x.tolist()})
headers = {"content-type": "application/json"}
json_response = requests.post('http://localhost:8501/v1/models/mobilenet:predict',
                              data=data, headers=headers)
predictions = numpy.array(json.loads(json_response.text)["predictions"])

$ python3 test.poy


predictions의 결과는 파이썬에서와 같습니다.

SavedModel 포맷

SavedModel은 변수값과 상수를 포함하고 직렬화된 시그니처와 이를 실행하는 데 필요한 상태를 담은 디렉토리입니다.

[root@www hopper]# ls ./mobilenet/1/
assets  saved_model.pb  variables
[root@www hopper]#

saved_model.pb 파일은 각각 하나의 함수로 된 이름있는 시그니처 세트를 포함합니다. 

variables 디렉토리에는 일반적인 훈련 체크포인트 파일이 있습니다 

[root@www hopper]# ls ./mobilenet/1/variables/
variables.data-00000-of-00001  variables.index
[root@www hopper]#


assets 디렉토리에는 텐서플로 그래프(TensorFlow graph)에서 사용되는 파일들, 예를 들어 상수 테이블을 초기화하는 데 사용되는 텍스트 파일들이 있습니다. 이번 예제에서는 사용되지 않습니다.

SavedModel은 텐서플로 그래프에서 사용되지 않는 파일을 위해 assets.extra 디렉토리를 가질 수 있는데, 예를 들면 사용자가 SavedModel과 함께 사용할 파일입니다. 
텐서플로 자체는 이 디렉토리를 사용하지 않습니다.






댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.