【问题标题】:How to load only a batch of images at a time in tensorflow?如何在张量流中一次只加载一批图像?
【发布时间】:2018-10-30 15:07:18
【问题描述】:

我正在从here 读取 cifar100 图像,我想从 pickle 文件中批量读取图像。使用此代码,我正在使用此行(已加载 %d 个示例。”% num)加载训练数据集中存在的所有图像。然后使用 tf.data 我可以读取批次。但是当它加载所有图像时,我的内存被利用它甚至没有开始训练。我正在使用类似于this的东西。这个链接使用tfrecords,我想使用pickle读取cifar数据。所以有谁知道我如何只能从cifar100 pickle文件中读取批量数据所以是不是我的记忆没有变满?

def read_data():
    def in_data():
        all_images = []
        all_labels = []
        with open("%s%s" % ("./data/cifar-100-python/", "train"),"rb") as fo:
            dict = pickle.load(fo, encoding='latin1')
            images = np.array(dict['data'])
            labels = np.array(dict['fine_labels'])
            num = images.shape[0]

            # images = normalize(images)
            images = images.astype(dtype=np.float32)
            labels = labels.astype(dtype=np.int32)
            images = np.reshape(images, [num, 3, 32, 32])
            images = np.transpose(images, [0, 2, 3, 1])

            print("Loaded %d examples." % num)
            #print('BeforeLables: ', labels)
            labels = one_hot_encode(labels)
            #print('afterLables: ', labels)
            all_images.append(images)
            all_labels.append(labels)
            # print('SIZE:', len(all_images))

        all_images = np.concatenate(all_images)
        all_labels = np.concatenate(all_labels)
        self.size = len(all_images)
        img_dataset = tf.data.Dataset.from_tensor_slices(all_images).batch(2)
        label_dataset = tf.data.Dataset.from_tensor_slices(all_labels).batch(2)

        dataset = tf.data.Dataset.zip((img_dataset, label_dataset)).repeat(None)

        images, labels = dataset.make_one_shot_iterator().get_next()
        print('image Shape:',images.shape)
        return images, labels
    return in_data

【问题讨论】:

    标签: python tensorflow deep-learning pickle


    【解决方案1】:

    我建议您阅读tutorial about importing data。有一个非常有用且非常相似的例子。在示例中,我们没有使用 from_tensor_slice 将图像数据嵌入到计算图中。相反,我们将文件名嵌入到图表中。

    此外,如果您的数据是单个太大而无法加载的数据,您必须预先将其拆分为多个文件

    【讨论】:

    • 嘿 Saket,谢谢您的回复。我是 tensorflow 的新手,不太确定如何拆分 pickle 文件。我尝试在网上搜索如何做到这一点,但我找不到任何与之相关的东西。如果你知道你能给我一些指点吗?因为对于 cifar-100,它们没有单独的文件名。
    • CIFAR-100 不大。为什么你认为内存已经耗尽?
    • 就像我打印这一行 Loaded %d examples 它告诉我加载了 50000 个示例。所以它正在加载整个数据集,但我想出了如何一次加载一个文件。我使用了 tfRecordLengthDataset 并且成功了。感谢您在之前的回复中提供的指针,它成功了。
    猜你喜欢
    • 2017-11-15
    • 2020-02-22
    • 1970-01-01
    • 2017-10-29
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多