【发布时间】:2016-04-28 14:34:25
【问题描述】:
有一个关于加载稀疏数据的小sn-p,但我不知道如何使用它。
SparseTensors 不能很好地处理队列。如果您使用 SparseTensors,则必须在批处理后使用 tf.parse_example 解码字符串记录(而不是在批处理前使用 tf.parse_single_example)。
我想我并不真正了解数据是如何加载的。
我要加载的数据是SVM Light格式
我的想法是将训练集转换为 TFRecords 文件格式,然后使用 tensorflow 加载转换后的数据。问题是我不知道我应该如何格式化我的数据,以便 tensorflow 将其解析为 sparseTensors。
这是从one GitHub 上提供的示例中提取的 sn-p:
def convert_to(images, labels, name):
num_examples = labels.shape[0]
if images.shape[0] != num_examples:
raise ValueError("Images size %d does not match label size %d." %
(images.shape[0], num_examples))
rows = images.shape[1]
cols = images.shape[2]
depth = images.shape[3]
filename = os.path.join(FLAGS.directory, name + '.tfrecords')
print('Writing', filename)
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
image_raw = images[index].tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(rows),
'width': _int64_feature(cols),
'depth': _int64_feature(depth),
'label': _int64_feature(int(labels[index])),
'image_raw': _bytes_feature(image_raw)}))
writer.write(example.SerializeToString())
writer.close()
它将图像数据编码为一个大块。我的数据的不同之处在于并非每个功能都被填充。我可能会以相同的方式保存我的数据,但我不确定这是使用这些功能的方式。
这无关紧要,因为另一方面我会解码,但是对于稀疏数据,有没有更好的方法呢?
关于读取,here 是读取密集张量数据的一个例子。
我知道我应该将tf.parse_single_example 与tf.parse_example 交换并在批处理后进行。
但是,我如何告诉 tensorflow 我的数据是稀疏的?如何将我拥有的特征索引与张量中的特征值相关联?如何在加载数据之前进行批处理?
编辑 1:
这是我尝试过的,我收到 ValueError: Shape () must have rank 1 错误:
from tqdm import *
def convert_to_tensor_file(path, out_file_name):
feature_set = set()
filename = os.path.join(FLAGS.directory, out_file_name + '.tfrecords')
writer = tf.python_io.TFRecordWriter(filename)
with open(path, 'r') as f:
for line in tqdm(f):
data = line.strip().split(' ')
features = {
"label": _int64_feature(int(data[0]))
}
for feature in data[1:]:
index, value = feature.split(':')
feature_set.add(index)
features[index] = _int64_feature(int(value))
example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(example.SerializeToString())
writer.close()
return feature_set
feature_set = convert_to_tensor_file(TRAIN, 'train')
def load_tensor_file(name):
filename = os.path.join(FLAGS.directory, name + '.tfrecords')
features = {
'label': tf.FixedLenFeature([], tf.int64),
}
for feature in feature_set:
features[feature] = tf.VarLenFeature(tf.int64)
with tf.name_scope('input'):
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_example(serialized_example, features=features)
load_tensor_file('train')
谢谢,
【问题讨论】:
标签: python tensorflow