【问题标题】:Tensorflow Estimator: Cache bottlenecksTensorflow Estimator:缓存瓶颈
【发布时间】:2019-02-03 22:52:06
【问题描述】:

在学习tensorflow图像分类教程时,首先缓存了每张图像的瓶颈:

def: cache_bottlenecks())

我已经使用 tensorflow 的 Estimator 重写了训练。这确实简化了所有代码。但是我想在这里缓存瓶颈功能。

这是我的model_fn。我想缓存dense 层的结果,这样我就可以对实际训练进行更改,而不必每次都计算瓶颈。

我怎样才能做到这一点?

def model_fn(features, labels, mode, params):
    is_training = mode == tf.estimator.ModeKeys.TRAIN

    num_classes = len(params['label_vocab'])

    module = hub.Module(params['module_spec'], trainable=is_training and params['train_module'])
    bottleneck_tensor = module(features['image'])

    with tf.name_scope('final_retrain_ops'):
        logits = tf.layers.dense(bottleneck_tensor, units=num_classes, trainable=is_training)  # save this?

    def train_op_fn(loss):
        optimizer = tf.train.AdamOptimizer()
        return optimizer.minimize(loss, global_step=tf.train.get_global_step())

    head = tf.contrib.estimator.multi_class_head(n_classes=num_classes, label_vocabulary=params['label_vocab'])

    return head.create_estimator_spec(
        features, mode, logits, labels, train_op_fn=train_op_fn
    )

【问题讨论】:

    标签: python tensorflow machine-learning classification


    【解决方案1】:

    TF 无法像您编写代码一样工作。你应该:

    1. 从原始网络将瓶颈导出到文件。
    2. 使用瓶颈结果作为输入,使用另一个网络来训练您的数据。

    【讨论】:

    • 你能举个例子吗?
    【解决方案2】:

    扩展@Feng 所说的内容:

    TFRecords and TFExamplesLoad Images

    这样的东西应该可以工作(未经测试):

    # Serialize the data into two tfrecord files
    tf.enable_eager_execution()
    feature_extractor = ...
    features_file = tf.python_io.TFRecordWriter('features.tfrec')
    label_file = tf.python_io.TFRecordWriter('labels.tfrec')
    
    for images, labels in dataset:
      features = feature_extractor(images)
      features_file.write(tf.serialize_tensor(features))
      label_file.write(tf.serialize_tensor(labels))
    
    # Parse the files and zip them together
    def parse(type, shape):
      _def parse(x):
        result = tf.parse_tensor(x, out_type=shape)
        result = tf.reshape(result, FEATURE_SHAPE)
        return result
      return parse
    
    features_ds = tf.data.TFRecordDataset('features.tfrec')
    features_ds = features_ds.map(parse(tf.float32, FEATURE_SHAPE), num_parallel_calls=AUTOTUNE)
    
    labels_ds = tf.data.TFRecordDataset('labels.tfrec')
    labels_ds = labels_ds.map(parse(tf.float32, FEATURE_SHAPE), num_parallel_calls=AUTOTUNE)
    
    ds = tf.data.Dataset.zip(features_ds, labels_ds)
    ds = ds.unbatch().shuffle().repeat().batch().prefetch()...
    

    您也可以使用 Dataset.cache 来完成此操作,但我不能 100% 确定细节。

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 2018-07-20
      • 2022-12-06
      • 2022-08-22
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多