我正在尝试训练一些嵌入并将我的数据集放入 tfrecord 形式。当我像这样将一个示例写入文件时:
tf_features = {
'given': int64_feature(given),
'context': bytes_feature(np.array(context).tostring())
}
writer.write(tf.train.Example(features=tf.train.Features(feature=tf_features)).SerializeToString())
其中int64_feature
和bytes_feature
被定义为:
def bytes_feature(val):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[val]))
def int64_feature(val):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[val]))
我打印出一个示例(给定,上下文)对,我得到类似:(698, [686, 439, 464, 775])
这很好。
但是,当我尝试像这样从同一个文件中读取时:
def parse_example(w, tf_example):
feats_dict = {
'given': tf.FixedLenFeature([], tf.int64, default_value=0),
'context': tf.FixedLenFeature([], tf.string)
}
features = tf.parse_single_example(tf_example, feats_dict)
context = tf.decode_raw(features['context'], tf.int64)
context_feats = dict()
ctx_idx = 0
for i in range(w):
if i == w//2: continue
context_feats['context%d' % ctx_idx] = context[ctx_idx]
ctx_idx += 1
return context_feats, features['given']
dataset = tf.data.TFRecordDataset([fname]).map(partial(parse_example, 5))
iterator = dataset.make_one_shot_iterator()
with tf.Session() as sess:
iter_features, iter_labels = iterator.get_next()
features = sess.run(iter_features)
labels = sess.run(iter_labels)
print(features, labels)
对于与以前相同的上下文对,我得到(464, [686, 439, 464, 775])
. 给定的标签始终是上下文标签中的第三个。
我已经盯着这段代码看了好几个小时,但我很难过。有谁知道发生了什么?