gpt4 book ai didi

tensorflow - 从 TFRecord 保存和读取可变大小列表

转载 作者:行者123 更新时间:2023-12-03 00:43:40 25 4
gpt4 key购买 nike

将稀疏向量存储到 TFRecord 的最佳方法是什么?我的稀疏向量仅包含 1 和 0,因此我决定只保存“1”所在位置的索引,如下所示:

example = tf.train.Example(
features=tf.train.Features(
feature={
'label': self._int64_feature(label),
'features' : self._int64_feature_list(values)
}
)
)

这里,values 是包含“ones”索引的列表。这个 values 数组有时包含数百个元素,有时根本没有。之后,我只需将序列化示例保存到 tfrecord。后来,我像这样读取 tfrecord:

features = tf.parse_single_example(
serialized_example,
features={
# We know the length of both fields. If not the
# tf.VarLenFeature could be used
'label': tf.FixedLenFeature([], dtype=tf.int64),
'features': tf.VarLenFeature(dtype=tf.int64)
}
)

label = features['label']
values = features['features']

这不起作用,因为 values 数组被识别为稀疏数组,并且我没有获取已保存的数据。在 tfrecords 中存储稀疏张量的最佳方法是什么以及如何读取它?

最佳答案

如果您只是序列化 1 的位置,您应该能够通过一些技巧得到正确的稀疏张量:

解析后的稀疏张量features['features']看起来像这样:

features['features'].indices: [[batch_id, 位置]...]

其中position是一个无用的枚举。

但您确实希望 feature['features'] 看起来像 [[batch_id, one_position], ...]

其中 one_position 是您在稀疏张量中指定的实际值。

所以:

indices = features['features'].indices
indices = tf.transpose(indices)
# Now looks like [[batch_id, batch_id, ...], [position, position, ...]]
indices = tf.stack([indices[0], features['features'].values])
# Now looks like [[batch_id, batch_id, ...], [one_position, one_position, ...]]
indices = tf.transpose(indices)
# Now looks like [[batch_id, one_position], [batch_id, one_position], ...]]
features['features'] = tf.SparseTensor(
indices=indices,
values=tf.ones(shape=tf.shape(indices)[:1])
dense_shape=1 + tf.reduce_max(indices, axis=[0])
)

瞧! features['features'] 现在表示一个矩阵,该矩阵是串联的一批稀疏向量。

注意:如果您想将其视为稠密张量,则必须执行 tf.sparse_to_dense 并且稠密张量将具有形状 [None, None] (这使得使用起来有点困难]。如果您知道最大可能的向量长度,您可能需要对其进行硬编码:dense_shape=[batch_size, max_vector_length]

关于tensorflow - 从 TFRecord 保存和读取可变大小列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37270697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com