使用十位数的字符串标签

2024-04-26 01:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我还在试着用自己的图像数据运行Tensorflow。 我可以用这个示例中的conevert_to()函数创建一个.tfrecords文件link

现在我想用示例link中的代码来训练网络。

但在read_and_decode()函数中失败。我在这个功能上的变化是:

label = tf.decode_raw(features['label'], tf.string) 

错误是:

TypeError: DataType string for attr 'out_type' not in list of allowed values: float32, float64, int32, uint8, int16, int8, int64

因此,如何1)阅读和2)使用字符串标签来训练tensorflow。


Tags: 文件to数据函数代码图像示例string
3条回答

^{}脚本创建一个.tfrecords文件,其中每个记录都是一个^{}协议缓冲区。该协议缓冲区支持使用^{} kind的字符串功能。

^{}操作用于将二进制字符串解析为图像数据;它不是为解析字符串(文本)标签而设计的。假设features['label']是一个tf.string张量,可以使用^{}操作将其转换为一个数字。TensorFlow程序中对字符串处理的其他支持有限,因此,如果需要执行一些更复杂的函数来将字符串标签转换为整数,则应在修改后的convert_to_tensor.py版本中使用Python执行此转换。

^{}脚本创建一个.tfrecords文件,其中每个记录都是一个^{}协议缓冲区。该协议缓冲区支持使用^{} kind的字符串功能。

^{}操作用于将二进制字符串解析为图像数据;它不是为解析字符串(文本)标签而设计的。假设features['label']是一个tf.string张量,可以使用^{}操作将其转换为一个数字。TensorFlow程序中对字符串处理的其他支持有限,因此如果需要执行一些更复杂的函数来将字符串标签转换为整数,则应在修改后的convert_to_tensor.py版本中使用Python执行此转换。

要添加到@mrry的答案中,假设字符串是ascii,您可以:

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def write_proto(cls, filepath, ..., item_id): # itemid is an ascii encodable string
    # ...
    with tf.python_io.TFRecordWriter(filepath) as writer:
        example = tf.train.Example(features=tf.train.Features(feature={
             # write it as a bytes array, supposing your string is `ascii`
            'item_id': _bytes_feature(bytes(item_id, encoding='ascii')), # python 3
            # ...
        }))
        writer.write(example.SerializeToString())

然后:

def parse_single_example(cls, example_proto, graph=None):
    features_dict = tf.parse_single_example(example_proto,
        features={'item_id': tf.FixedLenFeature([], tf.string),
        # ...
        })
    # decode as uint8 aka bytes
    instance.item_id = tf.decode_raw(features_dict['item_id'], tf.uint8)

然后,当您在会话中获得它时,将其转换回字符串:

item_id, ... = session.run(your_tfrecords_iterator.get_next())
print(str(item_id.flatten(), 'ascii')) # python 3

我从这个related so answer中接受了uint8技巧。对我有用,但欢迎评论/改进。

相关问题 更多 >

    热门问题