Python ML引擎谷歌云平台,解析部署模型内字符串的功能

Python ML引擎谷歌云平台,解析部署模型内字符串的功能,python,tensorflow,machine-learning,google-cloud-platform,google-cloud-ml,Python,Tensorflow,Machine Learning,Google Cloud Platform,Google Cloud Ml,我在ML引擎-谷歌云平台上使用TensorFlow来解决回归问题。我需要向ML引擎发送一个包含日期的张量字符串,比如“2018/06/05 23:00”,然后让我部署的模型从中提取基本上是(年、月、日、小时)的特征。上面的例子是(2018、06、05、23)。问题是,我需要在ML引擎中的部署模型中执行此操作,而不是在中间API中执行 首先,我做的是使普查模型教程适应我的回归问题。 在本教程中,他们通过终端使用gcloud命令gcloud ML Engine models create$mode

我在ML引擎-谷歌云平台上使用TensorFlow来解决回归问题。我需要向ML引擎发送一个包含日期的张量字符串,比如“2018/06/05 23:00”,然后让我部署的模型从中提取基本上是(年、月、日、小时)的特征。上面的例子是(2018、06、05、23)。问题是,我需要在ML引擎中的部署模型中执行此操作,而不是在中间API中执行

首先,我做的是使普查模型教程适应我的回归问题。

在本教程中,他们通过终端使用gcloud命令
gcloud ML Engine models create$model\u NAME…
在ML Engine中部署模型

下面,您将找到我发现的操纵字符串张量的方法,该字符串张量包含获取特征的日期

import tensorflow as tf
import numpy as np 
date_time = tf.placeholder(shape=(1,), dtype=tf.string, name="ph_date_time")

INPUT_COLUMNS=["year", "month", "day", "hour"]


split_date_time = tf.string_split(date_time, ' ')

date = split_date_time.values[0]
time = split_date_time.values[1]

split_date = tf.string_split([date], '-')
split_time = tf.string_split([time], ':')

year = split_date.values[0]
month = split_date.values[1]
day = split_date.values[2]
hours = split_time.values[0]
minutes = split_time.values[1]

year = tf.string_to_number(year, out_type=tf.int32, name="year_temp")
month = tf.string_to_number(month, out_type=tf.int32, name="month_temp")
day = tf.string_to_number(day, out_type=tf.int32, name="day_temp")
hours = tf.string_to_number(hours, out_type=tf.int32, name="hour_temp")
minutes = tf.string_to_number(minutes, out_type=tf.int32, name="minute_temp")

year = tf.expand_dims(year, 0, name="year")
month = tf.expand_dims(month, 0, name="month")
day = tf.expand_dims(day, 0, name="day")
hours = tf.expand_dims(hours, 0, name="hours")
minutes = tf.expand_dims(minutes, 0, name="minutes")

features = []
features = np.append(features, year)
features = np.append(features, month)
features = np.append(features, day)
features = np.append(features, hours)

# this would be the actual features to the deployed model
actual_features = dict(zip(INPUT_COLUMNS, features))



with tf.Session() as sess:
    year, month, day, hours, minutes = sess.run([year, month, day, hours, minutes], feed_dict={date_time: ["2018-12-31 22:59"]})
    print("Year =", year)
    print("Month =", month)
    print("Day =", day)
    print("Hours =", hours)
    print("Minutes =", minutes)

问题是我不知道如何告诉ML引擎使用上面的解析。我知道这与定义模型的
input\u fn
或用于导出模型的
service\u input\u fn
有关,但我不确定是否必须在两者或其中之一中粘贴我的代码,如有任何建议,将不胜感激,如果解释不清楚,请道歉。

遵循的一般模式是(请参阅):

  • 创建培训中使用的
    输入,通常使用
    tf.data.Dataset
    input\u fn
    应该调用helper函数来进行数据转换,就像您的代码中那样。输出将是一个功能名称字典,用于批量值
  • 输入的输出中的项目定义功能列。如有必要,进行特征交叉、bucketization等操作
  • 实例化估计器(例如,
    dnnRecessor
    ),将FeatureColumns传递给构造函数
  • 创建一个专门用于服务的
    input\u fn
    ,其中包含一个或多个
    tf.占位符
    ,其外部尺寸为
    None
    (可变批量大小)。从(1)调用相同的辅助函数来执行转换。返回一个
    tf.estimator.export.servingingputreceiver
    ,其中占位符作为输入,并且一个dict看起来应该与(1)中的dict相同
  • 你的特殊情况需要一些额外的细节。首先,您已将批量大小1硬编码到占位符中,相应的代码继续该假设。您的占位符必须具有
    shape=[None]

    不幸的是,您的代码是在假定shape为的情况下编写的,例如,
    split\u date\u time。值[0]
    将不再有效。我在下面的代码中添加了一个helper函数来解决这个问题

    下面是一些有望为您工作的代码:

    import tensorflow as tf
    
    # tf.string_split returns a SparseTensor. When using a variable batch size,
    # this can be difficult to further manipulate. In our case, we don't need
    # a SparseTensor, because we have a fixed number of elements each split.
    # So we do the split and convert the SparseTensor to a dense tensor.
    def fixed_split(batched_string_tensor, delimiter, num_cols):
        # When splitting a batch of elements, the values array is row-major, e.g.
        # ["2018-01-02", "2019-03-04"] becomes ["2018", "01", "02", "2019", "03", "04"].
        # So we simply split the string then reshape the array to create a dense
        # matrix with the same rows as the input, but split into columns, e.g.,
        # [["2018", "01", "02"], ["2019", "03", "04"]]
        split = tf.string_split(batched_string_tensor, delimiter)
        return tf.reshape(split.values, [-1, num_cols])
    
    
    def parse_dates(dates):  
        split_date_time = fixed_split(dates, ' ', 2)
    
        date = split_date_time[:, 0]
        time = split_date_time[:, 1]
    
        # The values of the resulting SparseTensor will alternate between year, month, and day
        split_date = fixed_split(date, '-', 3)
        split_time = fixed_split(time, ':', 2)
    
        year = split_date[:, 0]
        month = split_date[:, 1]
        day = split_date[:, 2]
        hours = split_time[:, 0]
        minutes = split_time[:, 1]
    
        year = tf.string_to_number(year, out_type=tf.int32, name="year_temp")
        month = tf.string_to_number(month, out_type=tf.int32, name="month_temp")
        day = tf.string_to_number(day, out_type=tf.int32, name="day_temp")
        hours = tf.string_to_number(hours, out_type=tf.int32, name="hour_temp")
        minutes = tf.string_to_number(minutes, out_type=tf.int32, name="minute_temp")
    
        return {"year": year, "month": month, "day": day, "hours": hours, "minutes": minutes}
    
    
    def training_input_fn():
        filenames = ["/var/data/file1.txt", "/var/data/file2.txt"]
        dataset = tf.data.TextLineDataset(filenames)    
        dataset.batch(BATCH_SIZE)
        return parse_dates(iterator.get_next())
    
    
    def serving_input_fn():
        date_strings = tf.placeholder(dtype=tf.string, shape=[None], name="date_strings")
        features = parse_dates(date_strings)
        return tf.estimator.export.ServingInputReceiver(features, date_strings)
    
    
    with tf.Session() as sess:
        date_time_list = ["2018-12-31 22:59", "2018-01-23 2:09"]
    
        date_strings = tf.placeholder(dtype=tf.string, shape=[None], name="date_strings")
        features = parse_dates(date_strings)
    
    
        fetches = [features[k] for k in ["year", "month", "day", "hours", "minutes"]]
        year, month, day, hours, minutes = sess.run(fetches, feed_dict={date_strings: date_time_list})
        print("Year =", year)
        print("Month =", month)
        print("Day =", day)
        print("Hours =", hours)
        print("Minutes =", minutes)
    

    在您的培训代码中,您是否使用tf.Estimator?“罐装”估计器还是您自己的定制模型?您使用的是功能列吗?我使用的是预先制作的估计器(DNNRegressor),所以是的,我使用的是一个罐装估计器。是的,我正在使用功能栏