데이터과학 삼학년

[tf 2.x] tf.keras 로 predict 결과 custom 하기 --> GCP ai-platform ( keyed model, serving_signature) 본문

Natural Language Processing

[tf 2.x] tf.keras 로 predict 결과 custom 하기 --> GCP ai-platform ( keyed model, serving_signature)

Dan-k 2020. 7. 8. 17:15
반응형
keras_keyed_model_text (1)
In [29]:
import os
import urllib

import pandas as pd

import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras import optimizers
from tensorflow.keras.layers import (
    Dense,
    Embedding,
    GRU
)
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.utils import to_categorical

print(tf.__version__)

from sklearn.model_selection import train_test_split
2.0.0
In [2]:
## naver 영화데이터 불러오기
urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt", filename="ratings_train.txt")
urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_test.txt", filename="ratings_test.txt")

train_data = pd.read_table('ratings_train.txt')
test_data = pd.read_table('ratings_test.txt')

train_data['document'] = train_data['document'].apply(str)

X = train_data.iloc[:2000,:].document
y = train_data.iloc[:2000,:].label
In [3]:
## X,y 데이터정제하기 -> 학습데이터 sequence vetor -> padded_sequence (max_len에 맞춰) / 레이블 데이터 : 카테고리컬 변수로 바꿔줌
tokenizer = Tokenizer()
tokenizer.fit_on_texts(X)
sequences = tokenizer.texts_to_sequences(X)  ### vovab을 만들고 각 단어마다 고유번호를 매긴 후 번호를 순서에 따라 매핑하는 방법
word_to_index = tokenizer.word_index
VOCAB_SIZE = len(word_to_index) + 1  ##  padding 할때 필요한 0 index 추가
MAX_LEN = max(len(seq) for seq in sequences)

def encode_labels(sources):
    classes = [source for source in sources]
    one_hots = to_categorical(classes)
    return one_hots

def create_sequences(texts, max_len=MAX_LEN):
    sequences = tokenizer.texts_to_sequences(texts)
    padded_sequences = pad_sequences(sequences, max_len, padding='post')
    return padded_sequences

X_train, X_valid, y_train, y_valid = train_test_split(create_sequences(X), encode_labels(y), test_size=0.1, random_state=42)
n_classes=2
optimizer = optimizers.Adam(learning_rate=0.01)
In [4]:
## 모델 만들기 : RNN
def build_rnn_model(vocab_size, embed_dim, max_len, units, n_classes):
    input_data = Input(shape=(max_len,), name="input_data", dtype=tf.int32)
    embed = Embedding(vocab_size + 1, embed_dim, input_length=max_len, mask_zero=True, dtype=tf.float32, name='Embedding')(input_data)
    gru = GRU(32, activation=tf.nn.relu, name="GRU")(embed)
    output = Dense(2, activation=tf.nn.softmax, name="output")(gru)
    model = Model(inputs=input_data, outputs=output)
    return model
In [5]:
rnn_model = build_rnn_model(VOCAB_SIZE, 32, MAX_LEN, 32, 2)
In [6]:
rnn_model.compile(
        optimizer='adam',
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )
In [7]:
tf.keras.utils.plot_model(rnn_model, show_shapes=True, dpi=90) 
Out[7]:
In [8]:
rnn_model.fit(X_train,y_train)
Train on 1800 samples
1800/1800 [==============================] - 11s 6ms/sample - loss: 0.6923 - accuracy: 0.5178
Out[8]:
<tensorflow.python.keras.callbacks.History at 0x7f11ebf1df98>
In [9]:
rnn_model.predict(X_valid)
Out[9]:
array([[0.50841326, 0.4915868 ],
       [0.5067442 , 0.49325582],
       [0.5192482 , 0.4807518 ],
       [0.50487745, 0.49512258],
       [0.5148147 , 0.4851853 ],
       [0.50024205, 0.49975792],
       [0.5185044 , 0.48149565],
       [0.5157503 , 0.48424968],
       [0.51632905, 0.4836709 ],
       [0.5065039 , 0.49349606],
       [0.5012201 , 0.49877992],
       [0.50591904, 0.49408102],
       [0.507366  , 0.492634  ],
       [0.5055834 , 0.49441656],
       [0.50581664, 0.49418333],
       [0.5123022 , 0.4876978 ],
       [0.50128275, 0.4987173 ],
       [0.50982875, 0.49017125],
       [0.5004489 , 0.49955118],
       [0.5045992 , 0.49540073],
       [0.49908608, 0.5009139 ],
       [0.51051235, 0.4894877 ],
       [0.50888985, 0.49111012],
       [0.5124319 , 0.48756814],
       [0.50858504, 0.491415  ],
       [0.50603163, 0.49396837],
       [0.51074874, 0.48925126],
       [0.5123927 , 0.4876073 ],
       [0.517825  , 0.48217496],
       [0.5098289 , 0.4901711 ],
       [0.505506  , 0.494494  ],
       [0.5124204 , 0.4875796 ],
       [0.5095761 , 0.4904239 ],
       [0.5137184 , 0.48628163],
       [0.51073813, 0.48926184],
       [0.5078678 , 0.4921322 ],
       [0.5130401 , 0.48695993],
       [0.50491196, 0.495088  ],
       [0.5175711 , 0.48242888],
       [0.5025944 , 0.49740556],
       [0.5087996 , 0.49120042],
       [0.509799  , 0.49020097],
       [0.508854  , 0.491146  ],
       [0.4977494 , 0.5022506 ],
       [0.5093708 , 0.49062923],
       [0.51038694, 0.48961303],
       [0.51746494, 0.482535  ],
       [0.5299198 , 0.47008026],
       [0.51336473, 0.48663527],
       [0.5164308 , 0.48356918],
       [0.51270306, 0.48729688],
       [0.5125142 , 0.48748574],
       [0.5027663 , 0.49723363],
       [0.50820494, 0.49179497],
       [0.50554115, 0.4944588 ],
       [0.51700455, 0.48299548],
       [0.51014644, 0.48985362],
       [0.5132231 , 0.48677695],
       [0.51182413, 0.48817593],
       [0.49880812, 0.5011919 ],
       [0.5015    , 0.49849993],
       [0.5119148 , 0.4880853 ],
       [0.5017311 , 0.49826884],
       [0.51243645, 0.48756355],
       [0.5125398 , 0.48746023],
       [0.5083392 , 0.4916608 ],
       [0.5117396 , 0.48826033],
       [0.51272213, 0.4872779 ],
       [0.5045426 , 0.4954574 ],
       [0.5074733 , 0.49252665],
       [0.51076514, 0.48923492],
       [0.50862414, 0.4913759 ],
       [0.4967672 , 0.5032327 ],
       [0.5077636 , 0.49223638],
       [0.50441784, 0.4955822 ],
       [0.50463337, 0.4953667 ],
       [0.5067239 , 0.49327612],
       [0.51765543, 0.4823446 ],
       [0.497228  , 0.502772  ],
       [0.50349647, 0.4965035 ],
       [0.51096624, 0.48903382],
       [0.50998414, 0.49001586],
       [0.5012201 , 0.49877992],
       [0.507225  , 0.49277502],
       [0.51129186, 0.48870808],
       [0.50321627, 0.49678373],
       [0.51245147, 0.4875486 ],
       [0.5147851 , 0.4852149 ],
       [0.50759375, 0.49240625],
       [0.51547426, 0.4845257 ],
       [0.51004744, 0.48995262],
       [0.51435596, 0.48564404],
       [0.4917984 , 0.50820166],
       [0.506278  , 0.49372205],
       [0.5092144 , 0.4907855 ],
       [0.50426674, 0.4957333 ],
       [0.52003855, 0.47996145],
       [0.50862545, 0.4913746 ],
       [0.50424117, 0.49575883],
       [0.5110553 , 0.4889447 ],
       [0.50523704, 0.49476293],
       [0.5150969 , 0.48490304],
       [0.5099879 , 0.49001214],
       [0.51073885, 0.48926115],
       [0.51143754, 0.48856246],
       [0.5168728 , 0.48312724],
       [0.509548  , 0.49045205],
       [0.51196176, 0.48803818],
       [0.5139012 , 0.4860988 ],
       [0.50246185, 0.4975381 ],
       [0.518115  , 0.48188505],
       [0.5001972 , 0.4998028 ],
       [0.51109654, 0.4889034 ],
       [0.5102715 , 0.48972854],
       [0.5036244 , 0.49637565],
       [0.5105439 , 0.48945606],
       [0.51640356, 0.48359638],
       [0.5037459 , 0.4962541 ],
       [0.5138225 , 0.48617744],
       [0.51818705, 0.48181292],
       [0.5099675 , 0.4900324 ],
       [0.5002099 , 0.49979007],
       [0.50565284, 0.49434716],
       [0.50691044, 0.49308956],
       [0.50724715, 0.49275285],
       [0.5121136 , 0.48788637],
       [0.5084043 , 0.49159572],
       [0.5103945 , 0.48960558],
       [0.5057047 , 0.49429527],
       [0.50962263, 0.4903773 ],
       [0.5160596 , 0.48394042],
       [0.5018187 , 0.49818134],
       [0.51504403, 0.48495594],
       [0.50826   , 0.49173996],
       [0.51699317, 0.48300683],
       [0.49426115, 0.50573885],
       [0.5107921 , 0.48920783],
       [0.5074518 , 0.49254823],
       [0.50910616, 0.49089384],
       [0.50875574, 0.49124432],
       [0.5134448 , 0.48655522],
       [0.515079  , 0.484921  ],
       [0.5004536 , 0.49954638],
       [0.50656205, 0.49343795],
       [0.50843626, 0.49156365],
       [0.5021872 , 0.4978128 ],
       [0.50996554, 0.49003446],
       [0.51410264, 0.48589736],
       [0.51494634, 0.4850537 ],
       [0.5101833 , 0.48981678],
       [0.51189834, 0.48810172],
       [0.5083132 , 0.49168685],
       [0.50730705, 0.49269292],
       [0.5084464 , 0.49155363],
       [0.51293766, 0.4870623 ],
       [0.51154083, 0.48845914],
       [0.5101384 , 0.4898616 ],
       [0.50179785, 0.4982022 ],
       [0.4996629 , 0.50033706],
       [0.5101601 , 0.48983994],
       [0.50856256, 0.49143744],
       [0.5064657 , 0.49353433],
       [0.5137765 , 0.48622352],
       [0.5065591 , 0.4934409 ],
       [0.5087221 , 0.4912778 ],
       [0.51021516, 0.4897848 ],
       [0.51068914, 0.48931086],
       [0.51101804, 0.48898202],
       [0.5158663 , 0.48413375],
       [0.50473994, 0.49526003],
       [0.51125735, 0.4887427 ],
       [0.5106115 , 0.48938853],
       [0.51071566, 0.48928434],
       [0.51170444, 0.48829558],
       [0.5125065 , 0.4874935 ],
       [0.51312655, 0.48687345],
       [0.5214359 , 0.47856408],
       [0.5091014 , 0.4908986 ],
       [0.51774895, 0.48225105],
       [0.5057522 , 0.49424788],
       [0.5100547 , 0.48994523],
       [0.5177594 , 0.48224065],
       [0.50580674, 0.49419326],
       [0.5052903 , 0.49470964],
       [0.5077816 , 0.49221843],
       [0.5125085 , 0.48749152],
       [0.5154821 , 0.48451787],
       [0.5144199 , 0.48558   ],
       [0.5110167 , 0.48898327],
       [0.4986297 , 0.5013704 ],
       [0.48945644, 0.5105435 ],
       [0.5098153 , 0.49018466],
       [0.51669014, 0.48330986],
       [0.50601214, 0.49398783],
       [0.51802015, 0.48197988],
       [0.4987409 , 0.5012591 ],
       [0.5053838 , 0.4946162 ],
       [0.4941588 , 0.50584126],
       [0.5152792 , 0.4847208 ],
       [0.5158984 , 0.48410162]], dtype=float32)

SavedModel and serving signature

  • Now save the model using tf.saved_model.save() into SavedModel format, not the older Keras H5 Format.
  • This will add a serving signature which we can then inspect.
  • The serving signature indicates exactly which input names and types are expected, and what will be output by the model
In [10]:
MODEL_EXPORT_PATH = './test_rnn_model/'
tf.saved_model.save(rnn_model, MODEL_EXPORT_PATH)
WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1781: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
INFO:tensorflow:Assets written to: ./test_rnn_model/assets
In [11]:
!saved_model_cli show --tag_set serve --signature_def serving_default --dir {MODEL_EXPORT_PATH}
The given SavedModel SignatureDef contains the following input(s):
  inputs['input_data'] tensor_info:
      dtype: DT_INT32
      shape: (-1, 38)
      name: serving_default_input_data:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['output'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 2)
      name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
In [12]:
loaded_model = tf.keras.models.load_model(MODEL_EXPORT_PATH)
In [13]:
loaded_model.signatures
Out[13]:
_SignatureMap({'serving_default': <tensorflow.python.saved_model.load._WrapperFunction object at 0x7f11787223c8>})
컴파일한 모델 VS 저장후 다시 불러온 모델
  • 컴파일한 오리지날 모델은 serving signature를 가지고 있지 않는다.
  • 일단 모델을 저장해야 serving signature를 갖게 되어서 저장후 다시 불러온 다음 serving_signature를 지정하는 것이다.
In [14]:
loaded_model
Out[14]:
<tensorflow.python.keras.saving.saved_model.load.Model at 0x7f117873d048>
In [15]:
rnn_model
Out[15]:
<tensorflow.python.keras.engine.training.Model at 0x7f11ec0cfef0>
  • loaded model 에서는 inference_function이 predict 의 역할을 대신한다. 그리고 이것은 keras의 Model.predict() 함수와 비슷하다.
  • 주목할 것은 output tensor의 name이 serving signature에 매칭된다는 것이다.
In [16]:
inference_function = loaded_model.signatures['serving_default']
In [17]:
inference_function # similar to keras.Model.predict()
Out[17]:
<tensorflow.python.saved_model.load._WrapperFunction at 0x7f11787223c8>
In [18]:
result = inference_function(tf.convert_to_tensor(X_valid))
print(result)
{'output': <tf.Tensor: id=9997, shape=(200, 2), dtype=float32, numpy=
array([[0.50841326, 0.4915868 ],
       [0.5067442 , 0.49325582],
       [0.5192482 , 0.4807518 ],
       [0.50487745, 0.49512258],
       [0.5148147 , 0.4851853 ],
       [0.50024205, 0.49975792],
       [0.5185044 , 0.48149565],
       [0.5157503 , 0.48424968],
       [0.51632905, 0.4836709 ],
       [0.5065039 , 0.49349606],
       [0.5012201 , 0.49877992],
       [0.50591904, 0.49408102],
       [0.507366  , 0.492634  ],
       [0.5055834 , 0.49441656],
       [0.50581664, 0.49418333],
       [0.5123022 , 0.4876978 ],
       [0.50128275, 0.4987173 ],
       [0.50982875, 0.49017125],
       [0.5004489 , 0.49955118],
       [0.5045992 , 0.49540073],
       [0.49908608, 0.5009139 ],
       [0.51051235, 0.4894877 ],
       [0.50888985, 0.49111012],
       [0.5124319 , 0.48756814],
       [0.50858504, 0.491415  ],
       [0.50603163, 0.49396837],
       [0.51074874, 0.48925126],
       [0.5123927 , 0.4876073 ],
       [0.517825  , 0.48217496],
       [0.5098289 , 0.4901711 ],
       [0.505506  , 0.494494  ],
       [0.5124204 , 0.4875796 ],
       [0.5095761 , 0.4904239 ],
       [0.5137184 , 0.48628163],
       [0.51073813, 0.48926184],
       [0.5078678 , 0.4921322 ],
       [0.5130401 , 0.48695993],
       [0.50491196, 0.495088  ],
       [0.5175711 , 0.48242888],
       [0.5025944 , 0.49740556],
       [0.5087996 , 0.49120042],
       [0.509799  , 0.49020097],
       [0.508854  , 0.491146  ],
       [0.4977494 , 0.5022506 ],
       [0.5093708 , 0.49062923],
       [0.51038694, 0.48961303],
       [0.51746494, 0.482535  ],
       [0.5299198 , 0.47008026],
       [0.51336473, 0.48663527],
       [0.5164308 , 0.48356918],
       [0.51270306, 0.48729688],
       [0.5125142 , 0.48748574],
       [0.5027663 , 0.49723363],
       [0.50820494, 0.49179497],
       [0.50554115, 0.4944588 ],
       [0.51700455, 0.48299548],
       [0.51014644, 0.48985362],
       [0.5132231 , 0.48677695],
       [0.51182413, 0.48817593],
       [0.49880812, 0.5011919 ],
       [0.5015    , 0.49849993],
       [0.5119148 , 0.4880853 ],
       [0.5017311 , 0.49826884],
       [0.51243645, 0.48756355],
       [0.5125398 , 0.48746023],
       [0.5083392 , 0.4916608 ],
       [0.5117396 , 0.48826033],
       [0.51272213, 0.4872779 ],
       [0.5045426 , 0.4954574 ],
       [0.5074733 , 0.49252665],
       [0.51076514, 0.48923492],
       [0.50862414, 0.4913759 ],
       [0.4967672 , 0.5032327 ],
       [0.5077636 , 0.49223638],
       [0.50441784, 0.4955822 ],
       [0.50463337, 0.4953667 ],
       [0.5067239 , 0.49327612],
       [0.51765543, 0.4823446 ],
       [0.497228  , 0.502772  ],
       [0.50349647, 0.4965035 ],
       [0.51096624, 0.48903382],
       [0.50998414, 0.49001586],
       [0.5012201 , 0.49877992],
       [0.507225  , 0.49277502],
       [0.51129186, 0.48870808],
       [0.50321627, 0.49678373],
       [0.51245147, 0.4875486 ],
       [0.5147851 , 0.4852149 ],
       [0.50759375, 0.49240625],
       [0.51547426, 0.4845257 ],
       [0.51004744, 0.48995262],
       [0.51435596, 0.48564404],
       [0.4917984 , 0.50820166],
       [0.506278  , 0.49372205],
       [0.5092144 , 0.4907855 ],
       [0.50426674, 0.4957333 ],
       [0.52003855, 0.47996145],
       [0.50862545, 0.4913746 ],
       [0.50424117, 0.49575883],
       [0.5110553 , 0.4889447 ],
       [0.50523704, 0.49476293],
       [0.5150969 , 0.48490304],
       [0.5099879 , 0.49001214],
       [0.51073885, 0.48926115],
       [0.51143754, 0.48856246],
       [0.5168728 , 0.48312724],
       [0.509548  , 0.49045205],
       [0.51196176, 0.48803818],
       [0.5139012 , 0.4860988 ],
       [0.50246185, 0.4975381 ],
       [0.518115  , 0.48188505],
       [0.5001972 , 0.4998028 ],
       [0.51109654, 0.4889034 ],
       [0.5102715 , 0.48972854],
       [0.5036244 , 0.49637565],
       [0.5105439 , 0.48945606],
       [0.51640356, 0.48359638],
       [0.5037459 , 0.4962541 ],
       [0.5138225 , 0.48617744],
       [0.51818705, 0.48181292],
       [0.5099675 , 0.4900324 ],
       [0.5002099 , 0.49979007],
       [0.50565284, 0.49434716],
       [0.50691044, 0.49308956],
       [0.50724715, 0.49275285],
       [0.5121136 , 0.48788637],
       [0.5084043 , 0.49159572],
       [0.5103945 , 0.48960558],
       [0.5057047 , 0.49429527],
       [0.50962263, 0.4903773 ],
       [0.5160596 , 0.48394042],
       [0.5018187 , 0.49818134],
       [0.51504403, 0.48495594],
       [0.50826   , 0.49173996],
       [0.51699317, 0.48300683],
       [0.49426115, 0.50573885],
       [0.5107921 , 0.48920783],
       [0.5074518 , 0.49254823],
       [0.50910616, 0.49089384],
       [0.50875574, 0.49124432],
       [0.5134448 , 0.48655522],
       [0.515079  , 0.484921  ],
       [0.5004536 , 0.49954638],
       [0.50656205, 0.49343795],
       [0.50843626, 0.49156365],
       [0.5021872 , 0.4978128 ],
       [0.50996554, 0.49003446],
       [0.51410264, 0.48589736],
       [0.51494634, 0.4850537 ],
       [0.5101833 , 0.48981678],
       [0.51189834, 0.48810172],
       [0.5083132 , 0.49168685],
       [0.50730705, 0.49269292],
       [0.5084464 , 0.49155363],
       [0.51293766, 0.4870623 ],
       [0.51154083, 0.48845914],
       [0.5101384 , 0.4898616 ],
       [0.50179785, 0.4982022 ],
       [0.4996629 , 0.50033706],
       [0.5101601 , 0.48983994],
       [0.50856256, 0.49143744],
       [0.5064657 , 0.49353433],
       [0.5137765 , 0.48622352],
       [0.5065591 , 0.4934409 ],
       [0.5087221 , 0.4912778 ],
       [0.51021516, 0.4897848 ],
       [0.51068914, 0.48931086],
       [0.51101804, 0.48898202],
       [0.5158663 , 0.48413375],
       [0.50473994, 0.49526003],
       [0.51125735, 0.4887427 ],
       [0.5106115 , 0.48938853],
       [0.51071566, 0.48928434],
       [0.51170444, 0.48829558],
       [0.5125065 , 0.4874935 ],
       [0.51312655, 0.48687345],
       [0.5214359 , 0.47856408],
       [0.5091014 , 0.4908986 ],
       [0.51774895, 0.48225105],
       [0.5057522 , 0.49424788],
       [0.5100547 , 0.48994523],
       [0.5177594 , 0.48224065],
       [0.50580674, 0.49419326],
       [0.5052903 , 0.49470964],
       [0.5077816 , 0.49221843],
       [0.5125085 , 0.48749152],
       [0.5154821 , 0.48451787],
       [0.5144199 , 0.48558   ],
       [0.5110167 , 0.48898327],
       [0.4986297 , 0.5013704 ],
       [0.48945644, 0.5105435 ],
       [0.5098153 , 0.49018466],
       [0.51669014, 0.48330986],
       [0.50601214, 0.49398783],
       [0.51802015, 0.48197988],
       [0.4987409 , 0.5012591 ],
       [0.5053838 , 0.4946162 ],
       [0.4941588 , 0.50584126],
       [0.5152792 , 0.4847208 ],
       [0.5158984 , 0.48410162]], dtype=float32)>}
In [19]:
result['output']
Out[19]:
<tf.Tensor: id=9997, shape=(200, 2), dtype=float32, numpy=
array([[0.50841326, 0.4915868 ],
       [0.5067442 , 0.49325582],
       [0.5192482 , 0.4807518 ],
       [0.50487745, 0.49512258],
       [0.5148147 , 0.4851853 ],
       [0.50024205, 0.49975792],
       [0.5185044 , 0.48149565],
       [0.5157503 , 0.48424968],
       [0.51632905, 0.4836709 ],
       [0.5065039 , 0.49349606],
       [0.5012201 , 0.49877992],
       [0.50591904, 0.49408102],
       [0.507366  , 0.492634  ],
       [0.5055834 , 0.49441656],
       [0.50581664, 0.49418333],
       [0.5123022 , 0.4876978 ],
       [0.50128275, 0.4987173 ],
       [0.50982875, 0.49017125],
       [0.5004489 , 0.49955118],
       [0.5045992 , 0.49540073],
       [0.49908608, 0.5009139 ],
       [0.51051235, 0.4894877 ],
       [0.50888985, 0.49111012],
       [0.5124319 , 0.48756814],
       [0.50858504, 0.491415  ],
       [0.50603163, 0.49396837],
       [0.51074874, 0.48925126],
       [0.5123927 , 0.4876073 ],
       [0.517825  , 0.48217496],
       [0.5098289 , 0.4901711 ],
       [0.505506  , 0.494494  ],
       [0.5124204 , 0.4875796 ],
       [0.5095761 , 0.4904239 ],
       [0.5137184 , 0.48628163],
       [0.51073813, 0.48926184],
       [0.5078678 , 0.4921322 ],
       [0.5130401 , 0.48695993],
       [0.50491196, 0.495088  ],
       [0.5175711 , 0.48242888],
       [0.5025944 , 0.49740556],
       [0.5087996 , 0.49120042],
       [0.509799  , 0.49020097],
       [0.508854  , 0.491146  ],
       [0.4977494 , 0.5022506 ],
       [0.5093708 , 0.49062923],
       [0.51038694, 0.48961303],
       [0.51746494, 0.482535  ],
       [0.5299198 , 0.47008026],
       [0.51336473, 0.48663527],
       [0.5164308 , 0.48356918],
       [0.51270306, 0.48729688],
       [0.5125142 , 0.48748574],
       [0.5027663 , 0.49723363],
       [0.50820494, 0.49179497],
       [0.50554115, 0.4944588 ],
       [0.51700455, 0.48299548],
       [0.51014644, 0.48985362],
       [0.5132231 , 0.48677695],
       [0.51182413, 0.48817593],
       [0.49880812, 0.5011919 ],
       [0.5015    , 0.49849993],
       [0.5119148 , 0.4880853 ],
       [0.5017311 , 0.49826884],
       [0.51243645, 0.48756355],
       [0.5125398 , 0.48746023],
       [0.5083392 , 0.4916608 ],
       [0.5117396 , 0.48826033],
       [0.51272213, 0.4872779 ],
       [0.5045426 , 0.4954574 ],
       [0.5074733 , 0.49252665],
       [0.51076514, 0.48923492],
       [0.50862414, 0.4913759 ],
       [0.4967672 , 0.5032327 ],
       [0.5077636 , 0.49223638],
       [0.50441784, 0.4955822 ],
       [0.50463337, 0.4953667 ],
       [0.5067239 , 0.49327612],
       [0.51765543, 0.4823446 ],
       [0.497228  , 0.502772  ],
       [0.50349647, 0.4965035 ],
       [0.51096624, 0.48903382],
       [0.50998414, 0.49001586],
       [0.5012201 , 0.49877992],
       [0.507225  , 0.49277502],
       [0.51129186, 0.48870808],
       [0.50321627, 0.49678373],
       [0.51245147, 0.4875486 ],
       [0.5147851 , 0.4852149 ],
       [0.50759375, 0.49240625],
       [0.51547426, 0.4845257 ],
       [0.51004744, 0.48995262],
       [0.51435596, 0.48564404],
       [0.4917984 , 0.50820166],
       [0.506278  , 0.49372205],
       [0.5092144 , 0.4907855 ],
       [0.50426674, 0.4957333 ],
       [0.52003855, 0.47996145],
       [0.50862545, 0.4913746 ],
       [0.50424117, 0.49575883],
       [0.5110553 , 0.4889447 ],
       [0.50523704, 0.49476293],
       [0.5150969 , 0.48490304],
       [0.5099879 , 0.49001214],
       [0.51073885, 0.48926115],
       [0.51143754, 0.48856246],
       [0.5168728 , 0.48312724],
       [0.509548  , 0.49045205],
       [0.51196176, 0.48803818],
       [0.5139012 , 0.4860988 ],
       [0.50246185, 0.4975381 ],
       [0.518115  , 0.48188505],
       [0.5001972 , 0.4998028 ],
       [0.51109654, 0.4889034 ],
       [0.5102715 , 0.48972854],
       [0.5036244 , 0.49637565],
       [0.5105439 , 0.48945606],
       [0.51640356, 0.48359638],
       [0.5037459 , 0.4962541 ],
       [0.5138225 , 0.48617744],
       [0.51818705, 0.48181292],
       [0.5099675 , 0.4900324 ],
       [0.5002099 , 0.49979007],
       [0.50565284, 0.49434716],
       [0.50691044, 0.49308956],
       [0.50724715, 0.49275285],
       [0.5121136 , 0.48788637],
       [0.5084043 , 0.49159572],
       [0.5103945 , 0.48960558],
       [0.5057047 , 0.49429527],
       [0.50962263, 0.4903773 ],
       [0.5160596 , 0.48394042],
       [0.5018187 , 0.49818134],
       [0.51504403, 0.48495594],
       [0.50826   , 0.49173996],
       [0.51699317, 0.48300683],
       [0.49426115, 0.50573885],
       [0.5107921 , 0.48920783],
       [0.5074518 , 0.49254823],
       [0.50910616, 0.49089384],
       [0.50875574, 0.49124432],
       [0.5134448 , 0.48655522],
       [0.515079  , 0.484921  ],
       [0.5004536 , 0.49954638],
       [0.50656205, 0.49343795],
       [0.50843626, 0.49156365],
       [0.5021872 , 0.4978128 ],
       [0.50996554, 0.49003446],
       [0.51410264, 0.48589736],
       [0.51494634, 0.4850537 ],
       [0.5101833 , 0.48981678],
       [0.51189834, 0.48810172],
       [0.5083132 , 0.49168685],
       [0.50730705, 0.49269292],
       [0.5084464 , 0.49155363],
       [0.51293766, 0.4870623 ],
       [0.51154083, 0.48845914],
       [0.5101384 , 0.4898616 ],
       [0.50179785, 0.4982022 ],
       [0.4996629 , 0.50033706],
       [0.5101601 , 0.48983994],
       [0.50856256, 0.49143744],
       [0.5064657 , 0.49353433],
       [0.5137765 , 0.48622352],
       [0.5065591 , 0.4934409 ],
       [0.5087221 , 0.4912778 ],
       [0.51021516, 0.4897848 ],
       [0.51068914, 0.48931086],
       [0.51101804, 0.48898202],
       [0.5158663 , 0.48413375],
       [0.50473994, 0.49526003],
       [0.51125735, 0.4887427 ],
       [0.5106115 , 0.48938853],
       [0.51071566, 0.48928434],
       [0.51170444, 0.48829558],
       [0.5125065 , 0.4874935 ],
       [0.51312655, 0.48687345],
       [0.5214359 , 0.47856408],
       [0.5091014 , 0.4908986 ],
       [0.51774895, 0.48225105],
       [0.5057522 , 0.49424788],
       [0.5100547 , 0.48994523],
       [0.5177594 , 0.48224065],
       [0.50580674, 0.49419326],
       [0.5052903 , 0.49470964],
       [0.5077816 , 0.49221843],
       [0.5125085 , 0.48749152],
       [0.5154821 , 0.48451787],
       [0.5144199 , 0.48558   ],
       [0.5110167 , 0.48898327],
       [0.4986297 , 0.5013704 ],
       [0.48945644, 0.5105435 ],
       [0.5098153 , 0.49018466],
       [0.51669014, 0.48330986],
       [0.50601214, 0.49398783],
       [0.51802015, 0.48197988],
       [0.4987409 , 0.5012591 ],
       [0.5053838 , 0.4946162 ],
       [0.4941588 , 0.50584126],
       [0.5152792 , 0.4847208 ],
       [0.5158984 , 0.48410162]], dtype=float32)>

Keyed Serving Function

  • Now we'll create a new serving function that accepts and outputs a unique instance key.
  • We use the fact that a Keras Model(x) call actually runs a prediction.
  • The training=False parameter is included only for clarity. Then we save the model as before but provide this function as our new serving signature.
In [20]:
@tf.function(input_signature=[tf.TensorSpec([None], dtype=tf.string), tf.TensorSpec([None, MAX_LEN], dtype=tf.int32)])
def keyed_prediction(key, data):
    pred = loaded_model(data, training=False)
    return {
        'output': pred,
        'key': key
    }
In [21]:
KEYED_EXPORT_PATH = './keyed_test_rnn_model/'
loaded_model.save(KEYED_EXPORT_PATH, signatures={'serving_default': keyed_prediction})
WARNING:tensorflow:Skipping full serialization of Keras layer <tensorflow.python.keras.saving.saved_model.load.InputLayer object at 0x7f117873a710>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <tensorflow.python.keras.saving.saved_model.load.Embedding object at 0x7f117873a860>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <tensorflow.python.keras.saving.saved_model.load.GRU object at 0x7f117873d5c0>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <tensorflow.python.keras.saving.saved_model.load.Dense object at 0x7f117873d908>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <tensorflow.python.keras.saving.saved_model.load.GRUCell object at 0x7f117873dd68>, because it is not built.
INFO:tensorflow:Assets written to: ./keyed_test_rnn_model/assets
In [22]:
!saved_model_cli show --tag_set serve --signature_def serving_default --dir {KEYED_EXPORT_PATH}
The given SavedModel SignatureDef contains the following input(s):
  inputs['data'] tensor_info:
      dtype: DT_INT32
      shape: (-1, 38)
      name: serving_default_data:0
  inputs['key'] tensor_info:
      dtype: DT_STRING
      shape: (-1)
      name: serving_default_key:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['key'] tensor_info:
      dtype: DT_STRING
      shape: (-1)
      name: StatefulPartitionedCall:0
  outputs['output'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 2)
      name: StatefulPartitionedCall:1
Method name is: tensorflow/serving/predict
In [23]:
keyed_model = tf.keras.models.load_model(KEYED_EXPORT_PATH)
In [24]:
keyed_model.predict(
    {
    'input_1': tf.convert_to_tensor([X_valid[0]], dtype=tf.int32),
    'key': tf.constant("1번유저")
    }
)
Out[24]:
array([[0.50841326, 0.49158677]], dtype=float32)
In [30]:
os.environ["MODEL_LOCATION"] = KEYED_EXPORT_PATH

GCP ai-platform에 적용하기

  • ai-platform에서는 serving_signature를 이용하여 prediction을 실행할 수 있으며, single signature 뿐만 아니라 dual signature도 지원한다.
  • Google Cloud AI Platform online and batch prediction support multiple signatures, as does TFServing.
In [ ]:
!gcloud ai-platform models create test_keyed_model \
  --regions us-central1
In [ ]:
!gcloud ai-platform versions create v2 \
       --model test_keyed_model --origin  ${MODEL_LOCATION} --staging-bucket gs://daehwan \
       --runtime-version 2.1
In [31]:
with open("keyed_txt_input.json", "w") as file:
    print('{"data": [494, 9251, 9252,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], "key": "id_1234"}', file=file)
In [32]:
!gcloud ai-platform predict --model test_keyed_model --json-instances keyed_txt_input.json --version v2 --signature-name serving_default
KEY      OUTPUT
id_1234  [0.49977055191993713, 0.5002294182777405]

위의 결과처럼 모델의 결과 뿐만 아니라 해당 key도 나오는 것을 볼 수 있다.

728x90
반응형
LIST
Comments