为什么这个简单的 tf.keras 模型在转换为 tensorflow 估计器后无法训练?

Why does this simple tf.keras model not train after converting to a tensorflow estimator?

我正在尝试使用 tf.keras.estimator.model_to_estimator 将 tf.keras 模型转换为张量流估计器,但生成的估计器似乎不可训练。

我已经尝试使用顺序和函数 tf.keras API 对 y = (x_1 + x_2)/2 进行建模,而 tf.keras 模型工作得很好,在转换为估算器后都不起作用。使用具有相同输入函数 tf.estimator.LinearRegressor 确实 有效,所以我认为问题不在于输入函数。

这是按顺序定义的 tf.keras 模型的最小工作示例:

import numpy as np
import tensorflow as tf
import functools

sample_size = 1000

x_train = np.random.randn(sample_size, 2).astype(np.float32)
y_train = np.mean(x_train, axis=1).astype(np.float32) 

x_test = np.random.randn(sample_size, 2).astype(np.float32)
y_test = np.mean(x_test, axis=1).astype(np.float32) 

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(2,), name="Prediction"))
adam = tf.keras.optimizers.Adam(lr=0.1)
model.compile(loss='MSE', optimizer=adam)
#model.fit(x=x_train, y=y_train, epochs=10, batch_size=64)  # This works

est = tf.keras.estimator.model_to_estimator(keras_model=model)

def train_input_fn(batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(({"Prediction_input": x_train}, y_train))
    return dataset.shuffle(sample_size).batch(batch_size).repeat()

def eval_input_fn(batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(({"Prediction_input": x_test}, y_test))
    return dataset.batch(batch_size)

est.train(input_fn=functools.partial(train_input_fn, 64), steps=10)

eval_metrics = est.evaluate(input_fn=functools.partial(eval_input_fn, 1))
print('Evaluation metrics:', eval_metrics)

估计器经过 10 个步骤的训练,这应该足以降低损失。据我所知,增加步骤数没有什么区别。

当我在 tensorflow 1.5.0 上 运行 时,我收到一条关于在编译 tf.keras 模型时调用 reduce_mean with keep_dims being deprecated 的警告,但是它训练得很好。

这是一个错误,还是我遗漏了什么?

事实证明,我需要做的就是将目标重塑为 (sample_size, 1) 的形状,并增加训练步骤的数量。我仍然不确定当目标具有形状 (sample_size, ) 时估算器在做什么,或者为什么这对固定估算器来说不是问题,但至少我知道如何避免这种情况。