【问题标题】:Reading binary data in float32读取 float32 中的二进制数据
【发布时间】:2016-02-06 00:18:16
【问题描述】:

我想根据时间信号的特征使用 Tensorflow 训练网络。数据在E 3 秒的时期被分割,每个时期都有F 的特征。因此,数据具有以下形式

Epoch | Feature 1 | Feature 2 | ... | Feature F |
-------------------------------------------------
1     | ..        | ..        |     | ..        |
      | ..        | ..        |     | ..        |
E     | ..        | ..        |     | ..        |

将数据加载到 Tensorflow,我正在尝试遵循 cifar 示例并使用 tf.FixedLengthRecordReader。因此,我获取了数据,并将其保存到类型为 float32 的二进制文件中,第一个标签用于第一个 epoch,然后是第一个 epoch 的 F 特征,然后是第二个,等等。

然而,将其读入 TensorFlow 对我来说是一个挑战。这是我的代码:

def read_data_file(file_queue):

    class DataRecord(object):
        pass

    result = DataRecord()

    #1 float32 as label => 4 bytes
    label_bytes = 4

    #NUM_FEATURES as float32 => 4 * NUM_FEATURES
    features_bytes = 4 * NUM_FEATURES

    #Create the read operator with the summed amount of bytes
    reader = tf.FixedLengthRecordReader(record_bytes=label_bytes+features_bytes)

    #Perform the operation
    result.key, value = reader.read(file_queue)

    #Decode the result from bytes to float32
    value_bytes = tf.decode_raw(value, tf.float32, little_endian=True)

    #Cast label to int for later
    result.label = tf.cast(tf.slice(value_bytes, [0], [label_bytes]), tf.int32)

    #Cast features to float32
    result.features = tf.cast(tf.slice(value_bytes, [label_bytes],
        [features_bytes]), tf.float32)

    print ('>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    print ('%s' % result.label)
    print ('%s' % result.features)
    print ('>>>>>>>>>>>>>>>>>>>>>>>>>>>')

打印输出为:

Tensor("Cast:0", shape=TensorShape([Dimension(4)]), dtype=int32)
Tensor("Slice_1:0", shape=TensorShape([Dimension(40)]), dtype=float32)

这让我感到惊讶,因为我已经将值转换为 float32,我预计尺寸分别为 1 和 10,这是实际数字,但它们是 4 和 40,对应于字节长度。

怎么会?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    我认为问题源于tf.decode_raw(value, tf.float32, little_endian=True) 返回tf.float32 类型的向量而不是字节向量。用于提取特征的切片大小应指定为浮点值计数(即NUM_FEATURES)而不是字节计数(features_bytes)。

    但是,您的标签是一个整数,而向量的其余部分包含浮点值,这一点略有不同。 TensorFlow 没有很多用于在二进制表示之间进行转换的工具(tf.decode_raw() 除外),因此您必须将字符串两次解码为不同的类型:

    # Decode the result from bytes to int32
    value_as_ints = tf.decode_raw(value, tf.int32, little_endian=True)
    result.label = value_as_ints[0]
    
    # Decode the result from bytes to float32
    value_as_floats = tf.decode_raw(value, tf.float32, little_endian=True)
    result.features = value_as_floats[1:1+NUM_FEATURES]
    

    请注意,这仅适用于 sizeof(tf.int32) == sizeof(tf.float32),一般情况下这不是真的。在更一般的情况下,更多的字符串操作工具将有助于切出原始value 的适当子字符串。不过,希望这足以让您继续前进。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 2018-03-08
      • 2017-07-10
      • 2013-10-17
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多