I saved the image date into tfrecord, but I cannot parse it with tensorflow dataset api.
My environment
- Ubuntu 18.04
- Python 3.6.8
- Jupyter Notebook
- Tensorflow 1.12.0
I saved the image data by following code,
writer = tf.python_io.TFRecordWriter('training.tfrecord')
# X_train: paths to the image, y_train: labels (0 or 1)
for image_path, label in zip(X_train, y_train):
image = cv2.imread(image_path)
image = cv2.resize(image, (150, 150)) / 255.0
ex = tf.train.Example(
features = tf.train.Features(
feature={
'image' : tf.train.Feature(float_list = tf.train.FloatList(value=image.ravel())),
'label' : tf.train.Feature(int64_list = tf.train.Int64List(value=[label]))
}
)
)
writer.write(ex.SerializeToString())
writer.close()
I tried getting a image from tfrecord file like that.
for record in tf.python_io.tf_record_iterator('test.tfrecord'):
example = tf.train.Example()
example.ParseFromString(record)
img = example.features.feature['image'].float_list.value
label = example.features.feature['label'].int64_list.value[0]
This method works.
But it doesn't when I use Dataset API to get images for my ML model.
def _parse_function(example_proto):
features = {
'label' : tf.FixedLenFeature((), tf.int64),
'image' : tf.FixedLenFeature((), tf.float32)
}
parsed_features = tf.parse_single_example(example_proto, features)
return parsed_features['image'], parsed_features['label']
def read_image(images, labels):
label = tf.cast(labels, tf.int32)
images = tf.cast(images, tf.float32)
image = tf.reshape(images, [150, 150, 3])
# read the data
dataset = tf.data.TFRecordDataset('training.tfrecord')
dataset = dataset.map(_parse_function)
dataset = dataset.map(read_image) # <- ERROR!
The error massage is
ValueError: Cannot reshape a tensor with 1 elements to shape [150,150,3] (67500 elements) for 'Reshape' (op: 'Reshape') with input shapes: [], [3] and with input tensors computed as partial shapes: input[1] = [150,150,3].
I though the cause of this error is the shape of the array is wrong, so I confirmed the element of the "dataset"
<MapDataset shapes: ((), ()), types: (tf.float32, tf.int64)>
"dataset" variable has no data. I don't know why it heppens.
Postscript
I tried the solution from Sharky, as a result,
def parse(example_proto):
features = {
'label' : tf.FixedLenFeature((), tf.string, ''),
'image' : tf.FixedLenFeature((), tf.string, '')
}
parsed_features = tf.parse_single_example(example_proto, features)
img_shape = tf.stack([150, 150, 3])
image = tf.decode_raw(parsed_features['image'], tf.float32)
image = tf.reshape(image, img_shape)
label = tf.decode_raw(parsed_features['label'], tf.int32)
label = tf.reshape(label, tf.stack([1]))
return image, label
works, I think. But I cannot get array from this MapDataset type object. How to do that?