2017-10-19 174 views
0

我正在使用tensorflow.contrib.learn.KMeansClustering進行K均值聚類。使用export_savedmodel導出KMeans模型以在ml引擎上部署

我可以使用它的默認模型預測本地,但因爲我想使用ml引擎在線預測,我必須將其導出到export_savedmodel格式。

我的地方谷歌很多的,但由於k-平均算法類不需要的功能列,所以我不知道如何建立正確的serving_input_fn爲export_savedmodel

這裏是我的代碼

# Generate input_fn 
def gen_input(data): 
    return tf.constant(data.as_matrix(), tf.float32, data.shape), None 

# Declare dataset + export model path 
TRAIN = 'train.csv' 
MODEL = 'model' 

# Read dataset 
body = pd.read_csv(
    file_io.FileIO(TRAIN, mode='r'), 
    delimiter=',', 
    header=None, 
    engine='python' 
) 

# Declare K-Means 
km = KMeansClustering(
    num_clusters=2, 
    model_dir=MODEL, 
    relative_tolerance=0.1 
) 

est = km.fit(input_fn=lambda: gen_input(body)) 

# This place is where I stuck 
fcols = [tf.contrib.layers.real_valued_column('x', dimension=5)] 
fspec = tf.contrib.layers.create_feature_spec_for_parsing(fcols) 
serving_input_fn = tf.contrib.learn.python.learn.\ 
        utils.input_fn_utils.build_parsing_serving_input_fn(fspec) 
est.export_savedmodel(MODEL, serving_input_fn) 

這裏我的玩具train.csv

1,2,3,4,5 
2,3,4,5,6 
3,4,5,6,7 
5,4,3,2,1 
7,6,5,4,3 
8,7,6,5,4 

導出模型有saved_model.pb的格式,它的變量文件夾

部署模型ML-引擎是成功的,但與同train.csv預測時,我得到了以下錯誤

{"error": "Prediction failed: Exception during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"Name: <unknown>, Feature: x (data type: float) is required but could not be found.\n\t [[Node: ParseExample/ParseExample = ParseExample[Ndense=1, Nsparse=0, Tdense=[DT_FLOAT], _output_shapes=-1,5, dense_shapes=5, sparse_types=[], _device=\"/job:localhost/replica:0/task:0/cpu:0\"](_arg_input_example_tensor_0_0, ParseExample/ParseExample/names, ParseExample/ParseExample/dense_keys_0, ParseExample/Const)]]\")"} 

我有這個奮鬥了一個月,而我發現所有的文件都是純API

我期待着您的諮詢

在此先感謝

回答

1

普查樣品shows如何爲CSV設置serving_input_fn。調整你的例子:

CSV_COLUMNS = ['feat1', 'feat2', 'feat3', 'feat4', 'feat5'] 
CSV_COLUMN_DEFAULTS = [[0.0],[0.0],[0.0],[0.0],[0.0]] 

def parse_csv(rows_string_tensor): 
    """Takes the string input tensor and returns a dict of rank-2 tensors.""" 

    # Takes a rank-1 tensor and converts it into rank-2 tensor 
    # Example if the data is ['csv,line,1', 'csv,line,2', ..] to 
    # [['csv,line,1'], ['csv,line,2']] which after parsing will result in a 
    # tuple of tensors: [['csv'], ['csv']], [['line'], ['line']], [[1], [2]] 
    row_columns = tf.expand_dims(rows_string_tensor, -1) 
    columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS) 
    features = dict(zip(CSV_COLUMNS, columns)) 

    return features 

def csv_serving_input_fn(): 
    """Build the serving inputs.""" 
    csv_row = tf.placeholder(
     shape=[None], 
     dtype=tf.string 
) 
    features = parse_csv(csv_row) 
    return tf.contrib.learn.InputFnOps(features, None, {'csv_row': csv_row}) 

# No need for fcols/fspec 
est.export_savedmodel(MODEL, serving_input_fn) 

TensorFlow 1.4將簡化至少一些此。

另外,考慮使用JSON,因爲這是更標準的服務方法。很高興根據要求提供詳細信息。

+0

非常感謝,它的工作原理:D –