【发布时间】:2020-04-25 03:45:02
【问题描述】:
我将卷积神经网络用于回归任务(即网络的最后一层有一个具有线性激活的神经元),这很好用(足够了)。当我尝试使用与tf.keras.estimator.model_to_estimator 打包的完全相同的模型时,估计器似乎很合适,但训练损失很快就会停止减少。裸 keras 模型的最终评估损失(每个 4 个 epoch 后)约为 0.4(平均绝对误差),估计器约为 2.5(平均绝对误差)。
为了演示这个问题,我将我的模型以裸机和估计器打包的形式应用于 MNIST 数据集(我知道 MNIST 是一项分类任务,将其作为回归任务处理并没有任何意义。这个例子应该仍然能说明我的观点。)
我觉得非常令人惊讶的是,当使用相同的方式将分类神经网络打包到估计器中时,裸 keras 模型及其打包的估计器版本表现同样出色(下面的示例代码中不包含分类案例) .差异仅发生在回归任务中。我想我要么遗漏了一些非常基本的东西,要么这种行为是由于 Tensorflow 中的一些错误造成的。
为了确保模型的输入之间存在尽可能少的差异,我将 MNIST 打包为 tf.data.Dataset,并从传递给估计器的输入函数中返回它。对于裸 Keras 模型,我使用相同的输入函数来获取 tf.Data.dataset 并直接将其交给 fit 函数。
# python 3.6. Tested with tensorflow-gpu-1.14 and tensorflow-cpu-2.0
import tensorflow as tf
import numpy as np
def get_model(IM_WIDTH=28, num_color_channels=1):
"""Create a very simple convolutional neural network using a tf.keras Functional Model."""
input = tf.keras.Input(shape=(IM_WIDTH, IM_WIDTH, num_color_channels))
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(input)
x = tf.keras.layers.MaxPooling2D(3)(x)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.MaxPooling2D(3)(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
output = tf.keras.layers.Dense(1, activation='linear')(x)
model = tf.keras.Model(inputs=[input], outputs=[output])
model.compile(optimizer='adam', loss="mae",
metrics=['mae'])
model.summary()
return model
def input_fun(train=True):
"""Load MNIST and return the training or test set as a tf.data.Dataset; Valid input function for tf.estimator"""
(train_images, train_labels), (eval_images, eval_labels) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape((60_000, 28, 28, 1)).astype(np.float32) / 255.
eval_images = eval_images.reshape((10_000, 28, 28, 1)).astype(np.float32) / 255.
# train_labels = train_labels.astype(np.float32) # these two lines don't affect behaviour.
# eval_labels = eval_labels.astype(np.float32)
# For a neural network with one neuron in the final layer, it doesn't seem to matter if target data is float or int.
if train:
dataset = tf.data.Dataset.from_tensor_slices((train_images, train_labels))
dataset = dataset.shuffle(buffer_size=100).repeat(None).batch(32).prefetch(1)
else:
dataset = tf.data.Dataset.from_tensor_slices((eval_images, eval_labels))
dataset = dataset.batch(32).prefetch(1) # note: prefetching does not affect behaviour
return dataset
model = get_model()
train_input_fn = lambda: input_fun(train=True)
eval_input_fn = lambda: input_fun(train=False)
NUM_EPOCHS, STEPS_PER_EPOCH = 4, 1875 # 1875 = number_of_train_images(=60.000) / batch_size(=32)
USE_ESTIMATOR = False # change this to compare model/estimator. Estimator performs much worse for no apparent reason
if USE_ESTIMATOR:
estimator = tf.keras.estimator.model_to_estimator(
keras_model=model, model_dir="model_directory",
config=tf.estimator.RunConfig(save_checkpoints_steps=200, save_summary_steps=200))
train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=STEPS_PER_EPOCH * NUM_EPOCHS)
eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn, throttle_secs=0)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
print("Training complete. Evaluating Estimator:")
print(estimator.evaluate(eval_input_fn))
# final train loss with estimator: ~2.5 (mean abs. error).
else:
dataset = train_input_fn()
model.fit(dataset, steps_per_epoch=STEPS_PER_EPOCH, epochs=NUM_EPOCHS)
print("Training complete. Evaluating Keras model:")
print(model.evaluate(eval_input_fn()))
# final train loss with Keras model: ~0.4 (mean abs. error).
【问题讨论】:
标签: python tensorflow conv-neural-network tensorflow-estimator tf.keras