TensorFlow WALS矩阵分解估计器如何正确export_savedmodel()?

时间:2019-04-22 02:28:06

标签: python tensorflow

我正在TensorFlow上使用this WALS矩阵分解模块。拟合估算器后,我试图使用export_savedmodel()方法保存模型,但无法提供正确的serving_input_fn参数。代码在这里:

from tensorflow.contrib.factorization.python.ops import wals as wals_lib

# dense input array that shows the user X item interactions
# here set as dummy array
dense_array = np.ones((10,10))
num_rows, num_cols = dense_array.shape
emebedding_dim = 5 # manually setting hidden factor

factorizer = wals_lib.WALSMatrixFactorization(num_rows, num_cols, embedding_dim, max_sweeps=10)

# this generate_input_fn() is not shown here but it's a copy of
# https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/factorization/python/ops/wals_test.py#L82
input_fn, _, _ = generate_input_fn(np_matrix=dense_array, batch_size=32, mode=model_fn.ModeKeys.TRAIN)
factorizer.fit(input_fn, steps=10)

# MY PROBLEM IS HERE
# How to define the correct serving input function?
factorizer.export_savedmodel('path/to/save/model', serving_input_fn=???)

这里最棘手的部分是,我相信WALS模块使用的是TensorFlow的较旧范例,其中serving_input_fn参数期望返回InputFnOps的可调用函数。但是,更新更新的估算器,例如this,需要一个返回tf.estimator.export.ServingInputReceivertf.estimator.export.TensorServingInputReceiver的函数。我承认我还不能完全熟练使用TensorFlow的输入功能,但是对于保存WALS估计器的特定用例的任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您对Tensorflow 1.x弃用的部分是正确的。对于WALSMatrixFactorization,您的serving_input_fn需要返回一个InputFnOps对象。因此,正确的输入函数应为:

def serving_input_receiver_fn():
    # some example input
    receiver_tensors = {'my_input': tf.placeholder(dtype=tf.string, shape=[None, 1], name='foo')}
    # some example feature that completely ignores the input
    features = {
        WALSMatrixFactorization.INPUT_ROWS: tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1., 2.], dense_shape=[3, 4]),
        WALSMatrixFactorization.INPUT_COLS: tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[3., 4.], dense_shape=[3, 4]),
        WALSMatrixFactorization.PROJECT_ROW: tf.constant(True),
    }
    return tf.contrib.learn.utils.InputFnOps(features, None, receiver_tensors)