今天我用我的图片制作了一个.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()
答案 0 :(得分:2)
我没有查看您的所有代码,但我认为我找到了数据集大小爆炸的原因。
您的转化过程如下所示:
图像文件通常是压缩的。无论是有损还是无损,它们都以节省空间的方式存储。当您解码图像并将原始字节保存为(未压缩的)文本时,您就会失去效率。
注意:我不知道您的输入管道是如何设置的,所以我在这里做了一些假设,但我相信我做对了。
问题在于,由于tfrecord文件中的解码图像,您拥有的每个示例都相当大。设置输入管道时,将读取数据并对其进行排队,以便管道的其他阶段可以处理它。我的想法是你的示例队列变得如此之大以至于内存不足,因为每个示例的大小都是如此。
您需要进行一些简单的更改来修复问题:将压缩文件的原始数据存储在.tfrecord中,然后直接在Tensorflow中进行解码。 该过程应如下所示:
打开二进制文件并将其内容作为字节字符串读出:
with(my_image_filename, 'rb') as fp:
raw_image = fp.read()
将raw_image
字节字符串写入.tfrecord文件
[tf.image.decode_image()](https://www.tensorflow.org/api_docs/python/tf/image/decode_image) or one of its more specific variants
。这样,在实际需要之前,您不会将解码图像存储在任何位置,因此您的队列也将保持合理的大小和tfrecord文件。
您正在混合使用OpenCV和Tensorflow,但这不是必需的。 Tensorflow拥有您首先将数据集转换为.tfrecord文件以及之后解码图像所需的全部内容,只需坚持使用Tensorflow的API就可以轻松实现IMO。 Here's the guide on how to set the conversion and the input pipeline,它显示了我上面描述的“典型的.tfrecord转换管道”,如果你有其他需求(比如从.csv文件中读取文件名),还有一些技巧。