【问题标题】:Read CSV file using tf.data is very slow, use tfrecords instead?使用 tf.data 读取 CSV 文件非常慢,使用 tfrecords 代替?
【发布时间】:2018-10-27 06:43:39
【问题描述】:

我有很多 CSV 文件,每条记录包含约 6000 列。第一列是标签,其余列应视为特征向量。我是 Tensorflow 的新手,我不知道如何将数据读取到具有所需格式的 Tensorflow Dataset 中。我目前正在运行以下代码:

DEFAULTS = []
n_features = 6170
for i in range(n_features+1):
  DEFAULTS.append([0.0])

def parse_csv(line):
    # line = line.replace('"', '')
    columns = tf.decode_csv(line, record_defaults=DEFAULTS)  # take a line at a time
    features = {'label': columns[-1], 'x': tf.stack(columns[:-1])}  # create a dictionary out of the features
    labels = features.pop('label')  # define the label

    return features, labels


def train_input_fn(data_file=sample_csv_file, batch_size=128):
    """Generate an input function for the Estimator."""
    # Extract lines from input files using the Dataset API.
    dataset = tf.data.TextLineDataset(data_file)
    dataset = dataset.map(parse_csv)
    dataset = dataset.shuffle(10000).repeat().batch(batch_size)
    return dataset.make_one_shot_iterator().get_next()

每个 CSV 文件都有大约 10K 条记录。我尝试在train_input_fn 上进行示例评估,作为labels = train_input_fn()[1].eval(session=sess)。这将获得 128 个标签,但大约需要 2 分钟

我是在使用一些冗余操作还是有更好的方法来做到这一点?

PS:我在 Spark Dataframe 中有原始数据。因此,如果 TFRecords 可以让事情变得更快,我也可以使用它。

【问题讨论】:

  • 如果我的回答解决了您的问题,请告诉我。谢谢

标签: python tensorflow tensorflow-datasets


【解决方案1】:

你做得对。但更快的方法是使用TFRecords,如下所示:

  1. 使用tf.python_io.TFRecordWriter: -- 读取 csv 文件并将其写入为 tfrecord 文件,如下所示:Tensorflow create a tfrecords file from csv

  2. 从 tfrecord 读取: --

    def _parse_function(proto):
       f = {
           "features": tf.FixedLenSequenceFeature([], tf.float32, default_value=0.0, allow_missing=True),
           "label": tf.FixedLenSequenceFeature([], tf.float32, default_value=0.0, allow_missing=True)
           }
           parsed_features = tf.parse_single_example(proto, f)
           features = parsed_features["features"]
           label = parsed_features["label"]
           return features, label
    
    
    dataset = tf.data.TFRecordDataset(['csv.tfrecords'])
    dataset = dataset.map(_parse_function)
    dataset = dataset.shuffle(10000).repeat().batch(128)
    iterator = dataset.make_one_shot_iterator()
    features, label = iterator.get_next()
    

我在随机生成的 csv 上运行了两个案例 (csv vs tfrecords)。 10个批次(每个128个样本)的csv直接读取总时间约为204s,而tfrecord的总时间约为0.22s

【讨论】:

  • 在我发布问题一小时后,我偶然发现了您在答案中提供的链接。因此,我没有回复您的答案。是的,我认为您的回答确实回答了这个问题。
猜你喜欢
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 2016-07-02
相关资源
最近更新 更多