【问题标题】:How to convert Float array/list to TFRecord?如何将浮点数组/列表转换为 TFRecord?
【发布时间】:2023-03-14 18:38:02
【问题描述】:

这是用于将数据转换为 TFRecord 的代码

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 _floats_feature(value):
   return tf.train.Feature(float_list=tf.train.FloatList(value=value))

with tf.python_io.TFRecordWriter("train.tfrecords") as writer:
    for row in train_data:
        prices, label, pip = row[0],row[1],row[2]
        prices = np.asarray(prices).astype(np.float32)
        example = tf.train.Example(features=tf.train.Features(feature={
                                           'prices': _floats_feature(prices),
                                           'label': _int64_feature(label[0]),
                                           'pip': _floats_feature(pip)
    }))
        writer.write(example.SerializeToString())

功能 价格 是一个形状数组 (1,288)。它转换成功!但是当使用解析函数和数据集 API 解码数据时。

def parse_func(serialized_data):
    keys_to_features = {'prices': tf.FixedLenFeature([], tf.float32),
                    'label': tf.FixedLenFeature([], tf.int64)}

    parsed_features = tf.parse_single_example(serialized_data, keys_to_features)
    return parsed_features['prices'],tf.one_hot(parsed_features['label'],2)

它给了我错误

C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES 在 example_parsing_ops.cc:240 失败:无效参数:键:价格。无法解析序列化的示例。 2018-03-31 15:37:11.443073: W C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES 在 example_parsing_ops.cc 失败:240 :无效参数:键:价格。无法解析序列化的示例。 2018-03-31 15:37:11.443313: W C:\tf_jenkins\workspace\rel-win\M\windows-gpu\ raise type(e)(node_def, op, message) PY\36\tensortensorflow.python.framework.errors_impl.InvalidArgumentError:键:价格。无法解析序列化的示例。 [[节点:ParseSingleExample/ParseSingleExample = ParseSingleExample[Tdense=[DT_INT64,DT_FLOAT],dense_keys=[“label”,“prices”],dense_shapes=[[],[]],num_sparse=0,sparse_keys=[],sparse_types =[]](arg0, ParseSingleExample/Const, ParseSingleExample/Const_1)]] [[节点:IteratorGetNext_1 = IteratorGetNextoutput_shapes=[[?], [?,2]], output_types=[DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0" ]]fl ow\core\framework\op_kernel.cc:1202] OP_REQUIRES 在 example_parsing_ops.cc:240 失败:无效参数:键:价格。无法解析序列化的示例。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    我发现了问题。不要使用tf.io.FixedLenFeature 来解析数组,而是使用tf.io.FixedLenSequenceFeature
    (对于 TensorFlow 1,使用 tf. 而不是 tf.io.

    【讨论】:

    • 您能否详细说明一下这实际上如何解决了您的问题以及您的代码看起来如何工作?
    • @JonDeaton 正如我上面提到的,我在使用 FixedLenFeatures 时遇到了错误。但是当我更改为 FixedLenSequenceFeature 时它起作用了。价格是一维数组。对于 tfrecord 编码,我使用 def _floats_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) 和解码: keys_to_features = {'prices': tf.FixedLenSequenceFeature([] ,dtype=tf.float32,allow_missing=True), 'label': tf.FixedLenFeature([], tf.int64)}
    • @SajadNorouzi 下面的答案似乎更正确。我设法让这两种方法都起作用。但是,我不确定文档是否像他所说的那样清晰。可能它同时已被编辑,但它似乎只是暗示 FixedLenSequenceFeature 应该只用于维度 2 或更高。可能值得编辑此答案以提及另一个答案,或者理清这两种方法中的哪一种是真正正确的,或者它们是否都是正确的。干杯!
    • 由于我的功能被存储为 tf.strings、tf.float32 或 tf.float64 的列表,因此遇到了类似的问题,因此提供相应的功能描述会有所帮助,例如"你的钥匙", tf.io.FixedLenSequenceFeature([], tf.string, allow_missing=True)
    【解决方案2】:

    如果您的特征是固定的一维数组,那么使用 tf.FixedLenSequenceFeature 根本不正确。如文档所述, tf.FixedLenSequenceFeature 用于维度为 2 或更高的输入数据。 在此示例中,您需要将价格数组展平为 (288,),然后对于解码部分,您需要提及数组维度。

    编码:

    example = tf.train.Example(features=tf.train.Features(feature={
                                           'prices': _floats_feature(prices.tolist()),
                                           'label': _int64_feature(label[0]),
                                           'pip': _floats_feature(pip)
    

    解码:

    keys_to_features = {'prices': tf.FixedLenFeature([288], tf.float32),
                    'label': tf.FixedLenFeature([], tf.int64)}
    

    【讨论】:

      【解决方案3】:

      您不能将 n 维数组存储为浮点特征,因为浮点特征是简单的列表。您必须通过执行prices.tolist()prices 扁平化为列表。如果你需要从扁平化的浮点特征中恢复n维数组,那么你可以做prices = np.reshape(float_feature, original_shape)

      【讨论】:

      • 它仍然不适用于扁平列表。我仍然收到上面的错误。
      【解决方案4】:

      我在不小心修改一些脚本时遇到了同样的问题,这是由于数据形状略有不同造成的。我不得不改变形状以匹配预期的形状,例如(A, B)(1, A, B)。我使用np.ravel() 进行扁平化。

      【讨论】:

        【解决方案5】:

        TFrecord 文件中读取float32 数据列表时,我也会遇到同样的事情。

        当用tf.FixedLenFeature 执行sess.run([time_tensor, frequency_tensor, frequency_weight_tensor]) 时,我得到Can't parse serialized Example,尽管tf.FixedLenSequenceFeature 似乎工作正常。

        我的读取文件的特征格式(工作的)如下: feature_format = { 'time': tf.FixedLenSequenceFeature([], tf.float32, allow_missing = True), 'frequencies': tf.FixedLenSequenceFeature([], tf.float32, allow_missing = True), 'frequency_weights': tf.FixedLenSequenceFeature([], tf.float32, allow_missing = True) }

        编码部分为:

        feature = { 'time': tf.train.Feature(float_list=tf.train.FloatList(value=[*some single value*]) ), 'frequencies': tf.train.Feature(float_list=tf.train.FloatList(value=*some_list*) ), 'frequency_weights': tf.train.Feature(float_list=tf.train.FloatList(value=*some_list*) ) }

        这发生在 Debian 机器上的 TensorFlow 1.12 上,没有 GPU 卸载(即只有 CPU 与 TensorFlow 一起使用)

        我这边有什么误用吗?还是代码或文档中的错误?如果这对任何人都有好处,我可以考虑贡献/上传任何修复程序......

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-20
          • 2019-03-31
          • 1970-01-01
          • 2019-10-31
          • 2012-05-04
          • 2013-10-20
          相关资源
          最近更新 更多