Обслуживание Tensorflow - формат SavedModel и передача информации в - PullRequest
0 голосов
/ 01 декабря 2018

Я действительно не понимаю этого!Я пытаюсь сохранить модель тензорного потока в формате SavedModel, готовую для использования с Tensorflow Serving.Чтобы сделать это, мне нужно определить входы и выходы, прежде чем я сохраню свою модель.

Я загружаю ранее сохраненную модель (ckpt) и хочу, чтобы в качестве входных данных использовался массивный массив.Это текстовый документ, который был преобразован в массив функций, который выглядит следующим образом:

array([0., 4., 0., ..., 0., 0., 0.])
<class 'numpy.ndarray'>

В качестве вывода я хочу оценить этот массив функций.

Вот моя модель:

hidden_layer_1 = {'weights':tf.Variable(tf.truncated_normal([len(train_x[0]), n_nodes_hl1], stddev=0.1)),'biases': tf.Variable(tf.constant(0.1,shape=[n_nodes_hl1]))}
hidden_layer_2 = {'weights': tf.Variable(tf.truncated_normal([n_nodes_hl1, n_nodes_hl2], stddev=0.1)),'biases': tf.Variable(tf.constant(0.1,shape=[n_nodes_hl2]))}
hidden_layer_3 = {'weights': tf.Variable(tf.truncated_normal([n_nodes_hl2, n_nodes_hl3], stddev=0.1)),'biases': tf.Variable(tf.constant(0.1,shape=[n_nodes_hl3]))}
output_layer = {'weights': tf.Variable(tf.truncated_normal([n_nodes_hl3, n_classes], stddev=0.1)),'biases': tf.Variable(tf.constant(0.1,shape=[n_classes]))}

def neural_network_model(data):
    l1 = tf.add(tf.matmul(data,hidden_layer_1['weights']), hidden_layer_1['biases'])
    l1 = tf.nn.relu(l1)
    l2 = tf.add(tf.matmul(l1,hidden_layer_2['weights']), hidden_layer_2['biases'])
    l2 = tf.nn.relu(l2)
    l3 = tf.add(tf.matmul(l2,hidden_layer_3['weights']), hidden_layer_3['biases'])
    l3 = tf.nn.relu(l3)
    output = tf.add(tf.matmul(l3,output_layer['weights']), output_layer['biases'],name='output')
    return output

А вот эта предварительно обученная модель, заполненная заполнителем, х.

x = tf.placeholder(tf.float32, [None, len(train_x[0])])
prediction = neural_network_model(x)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print("variables initialised") 
saver.restore(sess,'/path_to_model.ckpt')

result_tf = sess.run(tf.argmax(prediction.eval(feed_dict={x:[???]}),1))

Три «???»отметки, где я просто не понимаю.Я не знаю, как получить прогноз без feed_dict и не могу оценить заполнитель по отношению к самому себе, поэтому не уверен, куда идти!

Остальной код выглядит следующим образом:

#  Exports the model
export_path_base = FLAGS.export_model_dir
export_path = os.path.join(
    tf.compat.as_bytes(export_path_base),
    tf.compat.as_bytes(str(FLAGS.model_version)))
print('Exporting trained model to', export_path)
builder = tf.saved_model.builder.SavedModelBuilder(export_path)

# Creates the TensorInfo protobuf objects that encapsulates the input/output tensors
tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_output= tf.saved_model.utils.build_tensor_info(result_tf)

prediction_signature = (
    tf.saved_model.signature_def_utils.build_signature_def(
    inputs={'input': tensor_info_x},
    outputs={'output': tensor_info_output},
    method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

builder.add_meta_graph_and_variables(
    sess, [tf.saved_model.tag_constants.SERVING],
    signature_def_map={
        'classify_documents':
            prediction_signature,
    })
# export the model
builder.save(as_text=True)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...