【问题标题】:How to get the shape of a sparse tensor and convert it to list?如何获取稀疏张量的形状并将其转换为列表?
【发布时间】:2017-11-05 16:50:26
【问题描述】:

我有一些从文件中读取数据并将它们用作张量流网络的输入的代码。

import tensorflow as tf
reader = tf.TFRecordReader()
filename_queue = tf.train.string_input_producer(['/home/stuart/Desktop/tfrecords/m_6803.tfrecords'])
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
    serialized_example,
    features={
        'label': tf.FixedLenFeature([], tf.string),
        'user_behavior': tf.VarLenFeature(tf.float32),
    })
label = tf.cast(tf.decode_raw(features['label'], tf.uint8), tf.float32)
user_behavior = tf.cast(features['user_behavior'], tf.float32)
sess = tf.Session()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
print(user_behavior.get_shape().as_list()) # output: [None]
print(sess.run(tf.shape(user_behavior)) # output: (376), type: Tensor("Shape/Cast:0", shape=(1,), dtype=int32)

现在我需要获取张量“user_behavior”的形状,因为它因文件而异(我有多个文件要读取,尽管这里只有一个)。然后使用形状定义权重矩阵。 sess.run(tf.shape()) 可以工作,但它会将形状作为张量返回,该张量不能在 tf.Variable([], shape=[]) 中使用,因为这里的参数 shape 需要一个列表。虽然我知道tensor.get_shape().as_list() 返回一个列表,但由于我使用tf.VarLenFeature(),它会创建一个稀疏张量。如果我在其上使用此方法,则输出将为 [None]。那么有没有办法得到这个稀疏张量的形状,并用它来定义另一个张量的形状呢?

【问题讨论】:

    标签: python python-2.7 python-3.x tensorflow


    【解决方案1】:

    因为user_behavior是一个varlen特性。在tf.parse_single_examplemethod 之后它会变成一个稀疏张量。然后你可以很容易地通过user_behavior.dense_shape 方法得到形状。详细说明可以参考: https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      相关资源
      最近更新 更多