今天我做了一个.tfrecords
与我的图像文件。图像的宽度是2048,高度是1536。所有图像都差不多5.1GB,但是当我用它来制作.tfrecords
时,差不多 137 GB!更重要的是,当我用它来训练时,我收到类似 CUDA_ERROR_OUT_OF_MEMORY
的错误。
这是错误:
Total memory: 10.91GiB
Free memory: 10.45GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0: Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:01:00.0)
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 61835259904 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 61835259904
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
.........
我使用了最小的batch_size,但还是错误。有谁知道为什么?我的tfrecords
有问题吗?文件?
我制作的代码tfrecords
在这里:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import cv2
import os
import os.path
from PIL import Image
train_file = 'train.txt'
name = 'trainxx'
output_directory = './tfrecords'
resize_height = 1536
resize_width = 2048
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def load_file(examples_list_file):
lines = np.genfromtxt(examples_list_file, delimiter=" ", dtype=[('col1', 'S120'), ('col2', 'i8')])
examples = []
labels = []
for example, label in lines:
examples.append(example)
labels.append(label)
return np.asarray(examples), np.asarray(labels), len(lines)
def extract_image(filename, resize_height, resize_width):
image = cv2.imread(filename)
image = cv2.resize(image, (resize_height, resize_width))
b, g, r = cv2.split(image)
rgb_image = cv2.merge([r, g, b])
return rgb_image
def transform2tfrecord(train_file, name, output_directory, resize_height, resize_width):
if not os.path.exists(output_directory) or os.path.isfile(output_directory):
os.makedirs(output_directory)
_examples, _labels, examples_num = load_file(train_file)
filename = output_directory + "/" + name + '.tfrecords'
writer = tf.python_io.TFRecordWriter(filename)
for i, [example, label] in enumerate(zip(_examples, _labels)):
print('No.%d' % (i))
image = extract_image(example, resize_height, resize_width)
print('shape: %d, %d, %d, label: %d' % (image.shape[0], image.shape[1], image.shape[2], label))
image_raw = image.tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'image_raw': _bytes_feature(image_raw),
'height': _int64_feature(image.shape[0]),
'width': _int64_feature(image.shape[1]),
'depth': _int64_feature(image.shape[2]),
'label': _int64_feature(label)
}))
writer.write(example.SerializeToString())
writer.close()
def disp_tfrecords(tfrecord_list_file):
filename_queue = tf.train.string_input_producer([tfrecord_list_file])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'height': tf.FixedLenFeature([], tf.int64),
'width': tf.FixedLenFeature([], tf.int64),
'depth': tf.FixedLenFeature([], tf.int64),
'label': tf.FixedLenFeature([], tf.int64)
}
)
image = tf.decode_raw(features['image_raw'], tf.uint8)
# print(repr(image))
height = features['height']
width = features['width']
depth = features['depth']
label = tf.cast(features['label'], tf.int32)
init_op = tf.initialize_all_variables()
resultImg = []
resultLabel = []
with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(21):
image_eval = image.eval()
resultLabel.append(label.eval())
image_eval_reshape = image_eval.reshape([height.eval(), width.eval(), depth.eval()])
resultImg.append(image_eval_reshape)
pilimg = Image.fromarray(np.asarray(image_eval_reshape))
pilimg.show()
coord.request_stop()
coord.join(threads)
sess.close()
return resultImg, resultLabel
def read_tfrecord(filename_queuetemp):
filename_queue = tf.train.string_input_producer([filename_queuetemp])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'width': tf.FixedLenFeature([], tf.int64),
'depth': tf.FixedLenFeature([], tf.int64),
'label': tf.FixedLenFeature([], tf.int64)
}
)
image = tf.decode_raw(features['image_raw'], tf.uint8)
# image
tf.reshape(image, [256, 256, 3])
# normalize
image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
# label
label = tf.cast(features['label'], tf.int32)
return image, label
def test():
transform2tfrecord(train_file, name, output_directory, resize_height, resize_width)
img, label = disp_tfrecords(output_directory + '/' + name + '.tfrecords')
img, label = read_tfrecord(output_directory + '/' + name + '.tfrecords') 数
print label
if __name__ == '__main__':
test()
最佳答案
为什么您的数据集大小变大
我没有仔细检查您的所有代码,但我想我找到了数据集大小爆炸的原因。
您的转换过程如下所示:
- 获取文件名列表
- 打开图像文件并重新排序 channel
- 处理图像文件(重新缩放)
- 将数据字节以字符串形式写入.tfrecord文件<--问题点
图像文件通常被压缩。无论是有损还是无损,它们都以节省空间的方式存储。当您解码图像并将原始字节保存为(未压缩)文本时,您就失去了效率。
为什么你的代码会占用主机 RAM
注意:我不知道您的输入管道是如何设置的,因此我在这里做出一些假设,但我相信我的假设是正确的。
这里的问题是,由于 tfrecord 文件中的解码图像,您拥有的每个示例都相当大。当您设置输入管道时,数据将被读取并排队,以便管道的后续阶段可以处理它。我的想法是,由于每个示例的大小,您的示例队列会变得太大而导致内存不足。
典型的 .tfrecord 转换管道是什么样的
您需要进行一个简单的更改来解决您的问题:将压缩文件的原始数据存储在 .tfrecord 中,然后直接在 Tensorflow 中进行解码。 该过程应如下所示:
- 获取文件名列表
打开二进制文件并以字节字符串的形式读出其内容:
with(my_image_filename, 'rb') as fp: raw_image = fp.read()
写下
raw_image
字节字符串到.tfrecord文件- 在 Tensorflow 输入管道中,您将读取“raw_image”字节字符串张量并将其输入
<a href="https://www.tensorflow.org/api_docs/python/tf/image/decode_image" rel="noreferrer noopener nofollow">tf.image.decode_image()</a>
或其更具体的变体之一。
这样,在您真正需要解码图像之前,您不会将其存储在任何地方,因此您的队列和 tfrecord 文件将保持合理的大小。
有关设置的其他说明
您正在混合 OpenCV 和 Tensorflow,但这不是必需的。 Tensorflow 拥有您首先将数据集转换为 .tfrecord 文件,然后解码图像所需的一切,而且在我看来,只需坚持使用 Tensorflow 的 API 就简单得多。 Here's the guide on how to set the conversion and the input pipeline ,它显示了我上面描述的“典型的 .tfrecord 转换管道”,如果您有其他需求(例如从 .csv 文件中读取文件名),还可以添加一些技巧。
关于python - tensorflow:我的 .tfrecords 文件有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963721/