9

我正在研究在估计器的 model_fn 中使用预训练的 keras.applications 模型的问题。

在我的研究小组中,我们正在使用 Tensorflow 估计器,因为它们通过并行训练和评估、训练的热启动、易于服务等提供了许多优势。因此,我需要一个可以在估计器的 model_fn 中使用的解决方案。

基本上,我想在我的 model_fn 中使用预训练的图,尽管我可以使用 keras.applications 中的模型。不幸的是,到目前为止,我无法以合适的方式将 keras.applications 模型插入 model_fn。

我想使用没有顶层的视觉提取器(resnet50、mobilenet、nasnet ...)来提取特征向量,稍后我可能想要微调这个提取。这将排除使用视觉提取器作为 model_fn 之外的预处理步骤。

在对我的真实数据集进行了多次尝试之后,我回到了良好的旧 MNIST 并提出了一个最小的示例来表明我在寻找什么。我在stackoverflow上环顾四周,最初遵循了这个解释。

在下面的示例中,我尝试将具有 mobilenet 架构的 MNIST 数据集分类为视觉提取器。有两个传递特性的示例版本和一个根本不使用 keras 模型的示例。该代码非常接近官方的 TF custom_estimator 示例。只有数据集被缩减以轻松适应内存,图像被放大并转换为 rgb 以适应网络结构。

示例案例 1 和 2 导致训练损失停滞不前和评估持续损失。第三种情况表明,在没有模型的情况下,损失确实减少了(尽管整体性能很差,但可以预期)在这个例子中,我不是为了高性能!我只是想表明我被困在哪里,并希望有人能提供帮助。

想法和进一步的想法:

  • 评估损失是恒定的这一事实可能意味着模型根本没有传递输入。但是我该如何验证呢?在这种混合 tf/keras 的情况下,我无法让 tf.historgram 来绘制激活或权重。
  • 另一篇文章表明 keras 在后台保留一个会话。尽管由于估算器 API 为训练和评估构建了两个图表,但这可能会在后台变得混乱。
  • 如果有一种方法可以只使用带有权重的图形,我不需要 keras 模型的 OO 接口,但这怎么能工作呢?
  • 在 keras 后端设置学习阶段也会在不使用模型特征的情况下造成损失的颠簸,表明两个会话的问题,因此在下面注释掉。

我还在 github 上打开了一个问题,因为在我看来这个功能应该可以工作。

下面,您可以找到独立的示例。它应该在复制/粘贴后立即用完。非常感谢任何帮助!


        import tensorflow as tf
        import numpy as np

        from keras.datasets import mnist


        # switch to example 1/2/3
        EXAMPLE_CASE = 3

        # flag for initial weights loading of keras model
        _W_INIT = True


        def dense_net(features, labels, mode, params):
            # --- code to load a keras application ---

            # commenting in this line leads to a bump in the loss everytime the
            # evaluation is run, this indicating that keras does not handle well the
            # two sessions of the estimator API
            # tf.keras.backend.set_learning_phase(mode == tf.estimator.ModeKeys.TRAIN)
            global _W_INIT

            model = tf.keras.applications.MobileNet(
                input_tensor=features,
                input_shape=(128, 128, 3),
                include_top=False,
                pooling='avg',
                weights='imagenet' if _W_INIT else None)

            # only initialize weights once
            if _W_INIT:
                _W_INIT = False

            # switch cases
            if EXAMPLE_CASE == 1:
                # model.output is the same as model.layers[-1].output
                img = model.layers[-1].output
            elif EXAMPLE_CASE == 2:
                img = model(features)
            elif EXAMPLE_CASE == 3:
                # do not use keras features
                img = tf.keras.layers.Flatten()(features)
            else:
                raise NotImplementedError

            # --- regular code from here on ---
            for units in params['dense_layers']:
                img = tf.keras.layers.Dense(units=units, activation='relu')(img)

            logits = tf.keras.layers.Dense(units=10,
                                           activation='relu')(img)

            # compute predictions
            probs = tf.nn.softmax(logits)
            predicted_classes = tf.argmax(probs, 1)

            # compute loss
            loss = tf.losses.sparse_softmax_cross_entropy(labels, logits)

            acc = tf.metrics.accuracy(labels, predicted_classes)
            metrics = {'accuracy': acc}
            tf.summary.scalar('accuarcy', acc[1])

            if mode == tf.estimator.ModeKeys.EVAL:
                return tf.estimator.EstimatorSpec(
                    mode, loss=loss, eval_metric_ops=metrics)

            # create training operation
            assert mode == tf.estimator.ModeKeys.TRAIN

            optimizer = tf.train.AdagradOptimizer(learning_rate=0.01)
            train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)


        def prepare_dataset(in_tuple, n):
            feats = in_tuple[0][:n, :, :]
            labels = in_tuple[1][:n]
            feats = feats.astype(np.float32)
            feats /= 255
            labels = labels.astype(np.int32)
            return (feats, labels)


        def _parse_func(features, labels):
            feats = tf.expand_dims(features, -1)
            feats = tf.image.grayscale_to_rgb(feats)
            feats = tf.image.resize_images(feats, (128, 128))
            return (feats, labels)


        def load_mnist(n_train=10000, n_test=3000):
            train, test = mnist.load_data()
            train = prepare_dataset(train, n_train)
            test = prepare_dataset(test, n_test)
            return train, test


        def train_input_fn(imgs, labels, batch_size):
            dataset = tf.data.Dataset.from_tensor_slices((imgs, labels))
            dataset = dataset.map(_parse_func)
            dataset = dataset.shuffle(500)
            dataset = dataset.repeat().batch(batch_size)
            return dataset


        def eval_input_fn(imgs, labels, batch_size):
            dataset = tf.data.Dataset.from_tensor_slices((imgs, labels))
            dataset = dataset.map(_parse_func)
            dataset = dataset.batch(batch_size)
            return dataset


        def main(m_dir=None):
            # fetch data
            (x_train, y_train), (x_test, y_test) = load_mnist()

            train_spec = tf.estimator.TrainSpec(
                input_fn=lambda: train_input_fn(
                    x_train, y_train, 30),
                max_steps=150)

            eval_spec = tf.estimator.EvalSpec(
                input_fn=lambda: eval_input_fn(
                    x_test, y_test, 30),
                steps=100,
                start_delay_secs=0,
                throttle_secs=0)

            run_cfg = tf.estimator.RunConfig(
                model_dir=m_dir,
                tf_random_seed=2,
                save_summary_steps=2,
                save_checkpoints_steps=10,
                keep_checkpoint_max=1)

            # build network
            classifier = tf.estimator.Estimator(
                model_fn=dense_net,
                params={
                    'dense_layers': [256]},
                config=run_cfg)

            # fit the model
            tf.estimator.train_and_evaluate(
                classifier,
                train_spec,
                eval_spec)


        if __name__ == "__main__":
            main()
4

0 回答 0