Получение значения tf.placeholder / tf.varaible для определенной переменной внутри tf.Session() для модели google-ml-engine

Я использую Tensorflow с движком Google ML для прогнозирования.

Чтобы создать прогнозирование, нам нужно создать модель, обучить ее и экспортировать в формат.pb с другими метаданными графика, используя SaveModel . Я использую sklearn (sckiit) для интеграции алгоритма. Итак, финальная модель - это сочетание переменных tf и sklean.

У меня небольшая проблема с получением значения tf.placeholder / tf.varaible к определенной переменной внутри tf.Session(). Мой пример кода можно найти здесь:

#Note :  run the file  from root  of driver / directory as when we script try to save model in add_meta_graph_and_variables , it will give "ensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile" error if the path to folder is greater than 255 charac. in windows

#Note :  run the file  from root  of driver / directory as when we script try to save model in add_meta_graph_and_variables , it will give "ensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile" error if the path to folder is greater than 255 charac. in windows

#import data using pandas
#test with suicide random data set 

#hide warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import os.path
import tensorflow as tf
import time

import pandas
from sklearn.cross_validation import train_test_split


#time in Unix timestamp 
ts = str(int(time.time()))

# Basic model parameters as external flags.
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('input_dir', 'input', 'Input Directory.')
flags.DEFINE_string('output_dir', 'output', 'Output Directory.')



def train_and_predict():

    export_dir = os.path.join(FLAGS.output_dir, 'svmdl_'+ts)
    builder = tf.saved_model.builder.SavedModelBuilder(export_dir) 

    prediction_graph = tf.Graph()
    with prediction_graph.as_default():

        #input data - read from CSV
        csv_file = os.path.join(FLAGS.input_dir, 'suicide_random.csv');
        csv_data = pandas.read_csv(csv_file)  

        #split data 
        Y, X = csv_data['suicide_pr'], csv_data[['q1', 'q2', 'q3']].fillna(0)
        #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=35)
        X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)

        #features columns count 
        features_col_count = len(X.columns)

        #algorithm
        from sklearn import tree
        algorithm = tree.DecisionTreeClassifier()

        #variables define 
        # input_feedback = tf.placeholder(tf.float32, shape=[None, features_col_count])
        #input_feedback = tf.placeholder_with_default([0,0,0],shape=[None, features_col_count])
        #input_feedback = tf.placeholder_with_default([[0,0,0]],shape=[None, features_col_count])
        #input_feedback = tf.Variable([[0,0,0]])
        input_feedback = tf.Variable([[0,0,0]], name="input_feedback", validate_shape=False)


        with tf.Session(graph=prediction_graph) as sess:

            # Add the variable initializer Op.
            tf.global_variables_initializer().run()

            #train model 
            algorithm.fit(X_train, Y_train)

            #assign values for input data [convert tensors to actual data types that can be use under sklearn operations]
            #_input_feedback  =   input_feedback # error -  need to get placeholder value instead tensor object
            #_input_feedback  =   [[0,0,0]] # error -  need to get placeholder value instead tensor object
            _input_feedback  =   input_feedback.eval() # get tensor variable assigned value

            #prediction
            prediction = algorithm.predict( _input_feedback)
            prediction_probability = algorithm.predict_proba(_input_feedback) # give probability measure for each label ->category / class 


            #convert to TF variables - output variables need to be compatible with google ML engine
            tf_prediction = tf.Variable(prediction , name="tf_prediction", validate_shape=False)
            tf_prediction_probability = tf.Variable(prediction_probability, name="tf_prediction_probability", validate_shape=False)
            tf_input_feedback = tf.Variable(_input_feedback, name="tf_input_feedback", validate_shape=False)

            #initialize newly defined tensors 
            tf.global_variables_initializer().run() 

            print("Input Feedback : \n {0}".format(_input_feedback)) 
            print("Prediction values: \n {0}".format(prediction))
            print("Prediction probability: \n {0}".format(prediction_probability))

            inputs_info = { 'input_feedback' : tf.saved_model.utils.build_tensor_info( input_feedback)}
            output_info = { 
                                    'sucide_probability' : tf.saved_model.utils.build_tensor_info(tf_prediction),
                                    'score' : tf.saved_model.utils.build_tensor_info(tf_prediction_probability),
                                    'input_feedback' : tf.saved_model.utils.build_tensor_info(tf_input_feedback)
                                }

            signature_def = tf.saved_model.signature_def_utils.build_signature_def(
                inputs=inputs_info,
                outputs=output_info,
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
            )


            #save model 
            builder.add_meta_graph_and_variables(sess, tags=[tf.saved_model.tag_constants.SERVING],
                                       signature_def_map= {
                                            tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY : signature_def
                                        })


            builder.save()  




def main(_):
    train_and_predict()

if __name__ == '__main__':
    tf.app.run()

Для вышеупомянутой сохраненной модели результаты вызова API Google ml-engine "предсказывают" выглядят следующим образом;

Запрос:

Google ML Engine API - прогнозирование ввода CMD

Ответ: Google Engine Engine API - Прогноз выхода CMD

Мое требование состоит в том, что мне нужно заменить Google-ML-engine -> предугадывать ввод вызова API переменной "input_feedback". хотя я передаю другое значение для "input_feedback", оно всегда выводит / получает значение по умолчанию "[[0,0,0]" .

Я попытался заменить "input_feedback" на tf.placehodler и попытаться получить данные внутри сессии, используя feed_dict = {}, но не пошел дальше.

Любая обратная связь / помощь в том, как правильно сопоставить входные данные вызовов API с "input_feedback", очень ценится.

0 ответов

Другие вопросы по тегам