Tensorflow Estimator: Cache bottlenecks

Viewed 465

When following the tensorflow image classification tutorial, at first it caches the bottleneck of each image:

def: cache_bottlenecks())

I have rewritten the training using tensorflow's Estimator. This really simplified all the code. However I want to cache the bottleneck features here.

Here is my model_fn. I want to cache the results of the dense layer so I can make changes to the actual training without having to compute the bottlenecks each time.

How can I accomplish that?

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
    )
2 Answers

TF cannot work as you code. You should:

  1. Export bottleneck to file from the raw net.
  2. Use bottleneck result as input, use another net to train your data.

To expand on what @Feng said:

see TFRecords and TFExamples and Load Images

Something like this should work (untested):

# 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()...

You might also be able to do it using Dataset.cache, but I'm not 100% sure of the details.

Related