How to create `input_fn` using `read_batch_examples` with `num_epochs` set?

╄→尐↘猪︶ㄣ 提交于 2019-12-03 20:39:20

I have solved the above issue by creating a function specific to what's expected on an input_fn; it takes in a dense column and creates a SparseTensor without knowing shape. The function was made possible using tf.range and tf.shape. Without further ado, here is the working generic input_fn code that works independently of num_epochs being set:

def input_fn(batch_size):
    examples_op = tf.contrib.learn.read_batch_examples(
        FILE_NAMES,
        batch_size=batch_size,
        reader=tf.TextLineReader,
        num_epochs=1,
        parse_fn=lambda x: tf.decode_csv(x, [tf.constant([''], dtype=tf.string)] * len(HEADERS)))

    examples_dict = {}
    for i, header in enumerate(HEADERS):
        examples_dict[header] = examples_op[:, i]

    feature_cols = {k: tf.string_to_number(examples_dict[k], out_type=tf.float32)
                    for k in CONTINUOUS_FEATURES}

    feature_cols.update({k: dense_to_sparse(examples_dict[k])
                         for k in CATEGORICAL_FEATURES})

    label = tf.string_to_number(examples_dict[LABEL], out_type=tf.int32)

    return feature_cols, label


def dense_to_sparse(dense_tensor):
    indices = tf.to_int64(tf.transpose([tf.range(tf.shape(dense_tensor)[0]), tf.zeros_like(dense_tensor, dtype=tf.int32)]))
    values = dense_tensor
    shape = tf.to_int64([tf.shape(dense_tensor)[0], tf.constant(1)])

    return tf.SparseTensor(
        indices=indices,
        values=values,
        shape=shape
    )

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!