Tensorflow: 无法从tfrecord中提取文件名

我已经将图像、标签和文件名写入了一个tfrecords文件。当我尝试解码这个文件时,我无法将文件名从tf.string转换为字符串。

我编写用于转换为tfrecords文件的代码如下:

num_batches = 6batch_size = math.ceil(X_training.shape[0] / num_batches)for i in range(num_batches):    train_path = os.path.join("data","batch_" + str(i) + '.tfrecords')    writer = tf.python_io.TFRecordWriter(train_path)    start_row = i * batch_size    end_row = start_row + batch_size - 1    for idx in range(start_row, end_row):        try:            label = y_tr[idx]            filename = train_filenames[idx].tostring()            image = X_tr[idx]            image_raw = image.tostring()        except:            continue        example = tf.train.Example(            features=tf.train.Features(              feature={                'label': _int64_feature(label),                'filename': _bytes_feature(filename),                'image': _bytes_feature(image_raw),              }))        serialized = example.SerializeToString()        writer.write(serialized)

我有一个用于读取和解码tfrecords文件的函数:

def read_and_decode_single_example(filenames):    filename_queue = tf.train.string_input_producer(filenames)    reader = tf.TFRecordReader()    _, serialized_example = reader.read(filename_queue)    features = tf.parse_single_example(        serialized_example,        features={            'label': tf.FixedLenFeature([], tf.int64),            'filename': tf.FixedLenFeature([], tf.string),            'image': tf.FixedLenFeature([], tf.string)        })    label = features['label']    image = tf.decode_raw(features['image'], tf.uint8)    image = tf.reshape(image, [499, 499, 1])    filename = features['filename']    return label, image, filename

当我解码不同的批次时,返回的文件名看起来像这样:

b’P\x00\x00\x00_\x00\x00\x000\x00\x00\x000\x00\x00\x001\x00\x00\x004\x00\x00\x008\x00\x00\x00_\x00\x00\x00R\x00\x00\x00I\x00\x00\x00G\x00\x00\x00H\x00\x00\x00T\x00\x00\x00_\x00\x00\x00M\x00\x00\x00L\x00\x00\x00O\x00\x00\x00.\x00\x00\x00j\x00\x00\x00p\x00\x00\x00g\x00\x00\x00′

我在从tf.string解码时做错了什么?


回答:

对你的字节字符串调用.decode().replace('\x00', '')会产生’P_00148_RIGHT_MLO.jpg’。

在函数返回时添加解码和替换操作应该可以解决你的问题。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注