我正在开发CNN,将图像分类为4个结果。 我有一个问题要了解如何声明到tensorflow / serving的输入和输出,特别是保存模型。 在下面,您可以看到我的代码,但由于错误的predict_signature_def而无法解决某些问题,因此无法保存模型。 总的来说,我将对如何将模型输入/输出链接到张量输入/输出链接到SavedModel声明进行解释。
这里的代码显示模型是顺序的,输入形状为[64,64,3]
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot as plt
from scipy.misc import toimage
from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import tag_constants, signature_constants, signature_def_utils_impl
import cv2
model = Sequential()
model.add(InputLayer(input_shape=[64,64,3]))
...
4个类的输出:
model.add(Dense(4,activation='softmax'))
SavedModel是这样的:
x = model.input
y = model.output
#print('Results of Model', model.predict_proba(X))
prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({"inputs":x}, {"prediction":y})
valid_prediction_signature = tf.saved_model.signature_def_utils.is_valid_signature(prediction_signature)
if(valid_prediction_signature == False):
raise ValueError("Error: Prediction signature not valid!")
builder = saved_model_builder.SavedModelBuilder('./'+model_version)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
# Add the meta_graph and the variables to the builder
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:prediction_signature, },
legacy_init_op=legacy_init_op)
# save the graph
builder.save()
编译模型时,出现以下错误,但是没有任何线索表明模型尚未保存
WARNING:tensorflow:From cnn_garage.py:110: calling SavedModelBuilder.add_meta_graph_and_variables (from tensorflow.python.saved_model.builder_impl) with legacy_init_op is deprecated and will be removed in a future version.
Instructions for updating:
Pass your op to the equivalent parameter main_op instead.
Traceback (most recent call last):
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1292, in _do_call
return fn(*args)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1277, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1367, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Adam/beta_1
[[{{node save/SaveV2}} = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, Adam/beta_1, Adam/beta_2, Adam/decay, Adam/iterations, Adam/lr, conv2d_1/bias, conv2d_1/kernel, conv2d_2/bias, conv2d_2/kernel, conv2d_3/bias, conv2d_3/kernel, dense_1/bias, dense_1/kernel, dense_2/bias, dense_2/kernel)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "cnn_garage.py", line 110, in <module>
legacy_init_op=legacy_init_op)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/saved_model/builder_impl.py", line 418, in add_meta_graph_and_variables
saver.save(sess, variables_path, write_meta_graph=False, write_state=False)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1450, in save
raise exc
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1433, in save
{self.saver_def.filename_tensor_name: checkpoint_file})
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 887, in run
run_metadata_ptr)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1110, in _run
feed_dict_tensor, options, run_metadata)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1286, in _do_run
run_metadata)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1308, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Adam/beta_1
[[{{node save/SaveV2}} = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, Adam/beta_1, Adam/beta_2, Adam/decay, Adam/iterations, Adam/lr, conv2d_1/bias, conv2d_1/kernel, conv2d_2/bias, conv2d_2/kernel, conv2d_3/bias, conv2d_3/kernel, dense_1/bias, dense_1/kernel, dense_2/bias, dense_2/kernel)]]
Caused by op 'save/SaveV2', defined at:
File "cnn_garage.py", line 110, in <module>
legacy_init_op=legacy_init_op)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/saved_model/builder_impl.py", line 412, in add_meta_graph_and_variables
saver = self._maybe_create_saver(saver)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/saved_model/builder_impl.py", line 269, in _maybe_create_saver
allow_empty=True)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1094, in __init__
self.build()
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1106, in build
self._build(self._filename, build_save=True, build_restore=True)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1143, in _build
build_save=build_save, build_restore=build_restore)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 778, in _build_internal
save_tensor = self._AddShardedSaveOps(filename_tensor, per_device)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 369, in _AddShardedSaveOps
return self._AddShardedSaveOpsForV2(filename_tensor, per_device)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 343, in _AddShardedSaveOpsForV2
sharded_saves.append(self._AddSaveOps(sharded_filename, saveables))
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 284, in _AddSaveOps
save = self.save_op(filename_tensor, saveables)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 202, in save_op
tensors)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/ops/gen_io_ops.py", line 1690, in save_v2
shape_and_slices=shape_and_slices, tensors=tensors, name=name)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3272, in create_op
op_def=op_def)
File "/root/tensorflow3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1768, in __init__
self._traceback = tf_stack.extract_stack()
FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Adam/beta_1
[[{{node save/SaveV2}} = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, Adam/beta_1, Adam/beta_2, Adam/decay, Adam/iterations, Adam/lr, conv2d_1/bias, conv2d_1/kernel, conv2d_2/bias, conv2d_2/kernel, conv2d_3/bias, conv2d_3/kernel, dense_1/bias, dense_1/kernel, dense_2/bias, dense_2/kernel)]]