python - 在 TensorFlow 中使用 TF REcords 创建数据集
问题描述
我有一个 numpy 图像数组,每个图像都有一个句子。
我想创建一个具有图像-句子对的数据集。
我做了什么:
def npy_to_tfrecords(numpy_array, text_file, output_file):
f = open(text_file)
# write records to a tfrecords file
writer = tf.python_io.TFRecordWriter(output_file)
# Loop through all the features you want to write
for X, line in zip(numpy_array, f) :
#let say X is of np.array([[...][...]])
#let say y is of np.array[[0/1]]
txt = "{}".format(line[:-1])
txt = txt.encode()
# Feature contains a map of string to feature proto objects
feature = {}
feature['x'] = tf.train.Feature(float_list=tf.train.FloatList(value=X.flatten()))
feature['y'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[txt]))
# Construct the Example proto object
example = tf.train.Example(features=tf.train.Features(feature=feature))
# Serialize the example to a string
serialized = example.SerializeToString()
# write the serialized objec to the disk
writer.write(serialized)
writer.close()
现在,我想将其视为数据集并使用它:
然而,
def read_tfr_file(filename):
dataset = tf.data.TFRecordDataset(filename)
# for version 1.5 and above use tf.data.TFRecordDataset
# example proto decode
def _parse_function(example_proto):
keys_to_features = {'x':tf.FixedLenFeature([], tf.float32),
'y': tf.FixedLenSequenceFeature([], tf.string, allow_missing=True)}
parsed_features = tf.parse_single_example(example_proto, keys_to_features)
return parsed_features['x'], parsed_features['y']
# Parse the record into tensors.
dataset = dataset.map(_parse_function)
return dataset
通过这种方式读取记录,我总是得到 maperror 或者对象不可迭代,如何解决这个问题?
如何正确创建定长图像特征和变长句子的数据集?
解决方案
推荐阅读
- python - 我如何提供变量自定义元数据?
- java - Initialization-on-demand holder idiom - 什么时候加载类?
- airflow - 气流 > S3 连接在工作人员上失败
- python - 在张量流中将密集向量乘以稀疏矩阵
- java - Java 程序未进入 if 语句
- c++ - c++,我正在制作一个程序来计算一个字母在文件中出现的次数
- alloy - 找不到名称“div”...嗯?为什么?
- django - 更改最终用户的 postgres 密码
- python - 将 PyCharm 交互式 shell 中的最后一个命令移动到脚本
- acumatica - 折扣百分比或价格的一般查询