Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用TensorFlow加载稀疏数据?_Python_Tensorflow - Fatal编程技术网

Python 如何使用TensorFlow加载稀疏数据?

Python 如何使用TensorFlow加载稀疏数据?,python,tensorflow,Python,Tensorflow,有一个关于加载稀疏数据的小片段,但我不知道如何使用它 Sparsetensor不能很好地处理队列。如果使用sparsetensor,则必须在批处理后使用tf.parse_示例解码字符串记录(而不是在批处理前使用tf.parse_single_示例) 我想我真的不知道数据是如何加载的 我要加载的数据的格式是 我的想法是将训练集转换为TFRecords文件格式,然后使用tensorflow加载转换后的数据。问题是我不知道应该如何格式化数据,以便tensorflow将其解析为SparsetSenso

有一个关于加载稀疏数据的小片段,但我不知道如何使用它

Sparsetensor不能很好地处理队列。如果使用sparsetensor,则必须在批处理后使用tf.parse_示例解码字符串记录(而不是在批处理前使用tf.parse_single_示例)

我想我真的不知道数据是如何加载的

我要加载的数据的格式是

我的想法是将训练集转换为TFRecords文件格式,然后使用tensorflow加载转换后的数据。问题是我不知道应该如何格式化数据,以便tensorflow将其解析为SparsetSensor

下面是从GitHub上可用的示例中提取的一个片段:

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()
它将图像数据编码为一个大斑点。与我的数据不同的是,并不是每个功能都被填充。我可以用同样的方式保存数据,但我不确定这是使用这些功能的方式

这可能不重要,因为我将在另一方面解码东西,但有没有更好的方法来处理稀疏数据

至于读取,是读取密集张量数据的一个示例

我知道我应该用
tf.parse_single_example
交换
tf.parse_example
,并在批处理后执行

但是,如何告诉tensorflow我的数据是稀疏的?如何将我拥有的特征索引与张量中的特征值相关联?在加载数据之前如何进行批处理

编辑1:

下面是我尝试的,我得到一个
ValueError:Shape()必须有秩1
error:

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')

感谢您,

首先解释该文档的含义:

  • 对于密集数据,通常需要执行以下操作:

    序列化示例(来自读卡器)->
    解析单个示例
    ->
    批处理队列
    ->使用它

  • 对于稀疏数据,您当前需要执行以下操作:

    序列化示例(来自读卡器)->
    批处理队列
    ->
    解析示例
    ->使用它

  • 这方面的一个例子是:

    reader  = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    batch_serialized_examples = tf.shuffle_batch([serialized_example], batch_size)
    feature_to_type = {
      'label': tf.FixedLenFeature([1], dtype=tf.int64),
      'sparse_feature': tf.VarLenFeature(dtype=tf.int64)
    }
    features = tf.parse_example(batch_serialized_examples, feature_to_type)
    

    注意,
    shuffle\u batch
    接受一系列字符串并返回一批字符串<代码>标签在您的示例中应固定为秩==1的len。

    对于libsvm格式,如果您想要稀疏张量结果(而不是使用填充策略的密集张量结果),您可以编写和解析如下内容

    因此,通过这种方式,您将得到作为稠密张量的标签、作为两个稀疏张量的索引和值,您可以看到一个将libsvm格式写入TFRecord并从中读取用于mlp分类的自包含示例


    在TFRecords示例中存储索引和值,并使用
    SparseFeature
    进行解析。例如,要存储和加载的稀疏表示,请执行以下操作:

    [[0, 0, 0, 0, 0, 7],
     [0, 5, 0, 0, 0, 0],
     [0, 0, 0, 0, 9, 0],
     [0, 0, 0, 0, 0, 0]]
    
    这将创建一个TFRecords示例:

    my_example = tf.train.Example(features=tf.train.Features(feature={
        'index_0': tf.train.Feature(int64_list=tf.train.Int64List(value=[0, 1, 2])),
        'index_1': tf.train.Feature(int64_list=tf.train.Int64List(value=[5, 1, 4])),
        'values': tf.train.Feature(int64_list=tf.train.Int64List(value=[7, 5, 9]))
    }))
    my_example_str = my_example.SerializeToString()
    
    这将使用
    SparseFeature
    对其进行解析:

    my_example_features = {'sparse': tf.SparseFeature(index_key=['index_0', 'index_1'],
                                                      value_key='values',
                                                      dtype=tf.int64,
                                                      size=[4, 6])}
    serialized = tf.placeholder(tf.string)
    parsed = tf.parse_single_example(serialized, features=my_example_features)
    session.run(parsed, feed_dict={serialized: my_example_str})
    
    ## {'sparse': SparseTensorValue(indices=array([[0, 5], [1, 1], [2, 4]]),
    ##                              values=array([7, 5, 9]),
    ##                              dense_shape=array([4, 6]))}
    

    更多说明:

    如果要将稀疏值作为输入传递,则需要使用
    tf.sparse\u placeholder
    创建稀疏占位符

    然后应该使用
    tf.sparse\u to\u dense
    将稀疏张量转换为稠密张量

    为此,在feed_dict中输入数据时,需要显式传递稀疏矩阵的值、形状和索引,然后在图形中使用
    tf.sparse_to_dense

    在图表中:

    dense = tf.sparse_to_dense(
        sparse_indices=sparse_placeholder.indices,
        output_shape=sparse_placeholder.shape,
        sparse_values=sparse_placeholder.values,
    validate_indices=False)
    
    在提要中:

    sparse_placeholder:tf.SparseTensorValue(indices=indices,values=sparse_values,dense_shape=sparse_shape)
    

    您可以使用
    weighted\u category\u列
    来解析
    索引
    ,例如

    categorical_column = tf.feature_column.categorical_column_with_identity(
                key='index', num_buckets=your_feature_dim)
    sparse_columns = tf.feature_column.weighted_categorical_column(
        categorical_column=categorical_column, weight_feature_key='value')
    
    然后将
    稀疏列
    馈送给线性模型估计器,在馈送给DNN之前,请使用嵌入,例如

    dense_columns = tf.feature_column.embedding_column(sparse_columns, your_embedding_dim)
    

    然后将
    密集列
    输入到您的DNN估计器

    Thx,对于答案,这又提出了几个问题:批处理步骤用于什么?在这里,稀疏特征的定义是什么?是特征向量,一个包含多个特征的向量,还是特征向量的一个元素?在阅读了这个anwser和博客之后,我仍然没有弄清楚如何加载一维稀疏表示?将稀疏数据转换为稠密数据是否会在训练时否定稀疏数据结构的点?
    dense_columns = tf.feature_column.embedding_column(sparse_columns, your_embedding_dim)