tf.shape()返回2-d张量而不是1-d

时间:2017-12-16 09:31:32

标签: machine-learning tensorflow deep-learning tensor

在tensorflow API tf.shape中,它说

  

此操作返回表示输入形状的1-D整数张量。

然而,当我打电话

features = {
    'k_mask': tf.VarLenFeature(tf.int64),
    'features': tf.VarLenFeature(tf.int64),
    'labels': tf.FixedLenFeature([3], tf.int64),
    'k_ids': tf.VarLenFeature(tf.int64)
}
parsed_features = tf.parse_single_example(example_proto, features)
features_index = tf.sparse_tensor_to_dense(parsed_features['features'])
print(sess.run(tf.shape(features_index)))

我得到[[59]]的结果,这是一个二维整数张量。 feature_index可以打印为

[[ 6217  5882 17223 17235  6008  3580 17233  6038 16340  6116  5458  5747
   5957  5755 17238  5745  6030  6078  5786  4373  5888 16284  3574  3569
   5811  6117  5748 17228  5810  5833  5823  5885  5986  6034  5756  6105
   5832  6199  6087  5744  6037  5933  6095  5785 16290  6124  3559  5787
   6111  3570  6109 17322  3840  5962  3566 16950  6006  3584  6011]]

我认为这是一个正常的[1,59]张量。我尝试以下代码:

v1 = tf.constant([[4,3,1,7]])
print(sess.run(v1)) # [[4 3 1 7]]
print(sess.run(tf.shape(v1))) # [1 4]

看起来像预期的那样。

我希望将feature_index转换为[59,1]的形状。谁会知道为什么返回类型是2-d以及如何转换张量?

1 个答案:

答案 0 :(得分:0)

最后解决如下:

features_index = tf.sparse_tensor_to_dense(parsed_features['features'])
indices = tf.reshape(features_index, [tf.shape(features_index)[0], -1])

获取shape(indices) == [59,1]