2017-02-09 41 views
1

我試圖將張量(其中一些是稀疏的)張量輸入RAM中的模型。我創建了一個PaddingFIFOQueue,我在其中假設稀疏值不能通過其他方法從RAM進行批處理(如果不是這種情況,請讓我知道),我將排列稀疏張量的索引,值和形狀。它們需要填充,因爲序列長度各不相同。從出列的一批值,索引,形狀創建SparseTensor

我離隊以下...

indices = [batch size, None, 2] 
values = [batch size, None] 
shapes = [batch size, 2] 

我試圖使用這些值來創建一個SparseTensor,但我得到了下面的錯誤。

ValueError: Shape (512, ?, 2) must have rank 2 

的代碼如下的主要部分...

indices, values, shapes = self.queue.dequeue_many(batch_size) 
sp_tensor = tf.SparseTensor(indices, values, shapes) 

我想這是因爲SparseTensor期待一個秩2張量,而不是一個批次秩2張量(由所指示的錯誤消息),但我不知道如何轉換批處理。

+0

你有沒有考慮過[sparse_merge](https://www.tensorflow.org/api_docs/python/sparse_ops/conversion#sparse_merge)? –

+0

我出院的張量是密集的張量。 'sparse_merge'似乎是什麼輸入稀疏張量。 'sp_ids:具有int32或int64類型的值屬性的SparseTensor。 sp_values:任何類型的ASparseTensor.' – user7542570

+0

對,我很愚蠢。我已經把答案放在一起。 –

回答

1

這是可能與位瓷磚和重塑:

import tensorflow as tf 

def sparse_tensor_merge(indices, values, shape): 
    """Creates a SparseTensor from batched indices, values, and shapes. 

    Args: 
    indices: A [batch_size, N, D] integer Tensor. 
    values: A [batch_size, N] Tensor of any dtype. 
    shape: A [batch_size, D] Integer Tensor. 
    Returns: 
    A SparseTensor of dimension D + 1 with batch_size as its first dimension. 
    """ 
    merged_shape = tf.reduce_max(shape, axis=0) 
    batch_size, elements, shape_dim = tf.unstack(tf.shape(indices)) 
    index_range_tiled = tf.tile(tf.range(batch_size)[..., None], 
           tf.stack([1, elements]))[..., None] 
    merged_indices = tf.reshape(
     tf.concat([tf.cast(index_range_tiled, tf.int64), indices], axis=2), 
     [-1, 1 + tf.size(merged_shape)]) 
    merged_values = tf.reshape(values, [-1]) 
    return tf.SparseTensor(
     merged_indices, merged_values, 
     tf.concat([[tf.cast(batch_size, tf.int64)], merged_shape], axis=0)) 

因此,例如:

batch_indices = tf.constant(
    [[[0, 0], [0, 1]], 
    [[0, 0], [1, 1]]], dtype=tf.int64) 
batch_values = tf.constant(
    [[0.1, 0.2], 
    [0.3, 0.4]]) 
batch_shapes = tf.constant(
    [[2, 2], 
    [3, 2]], dtype=tf.int64) 

merged = sparse_tensor_merge(batch_indices, batch_values, batch_shapes) 

with tf.Session(): 
    print(merged.eval()) 

打印:

SparseTensorValue(indices=array([[0, 0, 0], 
     [0, 0, 1], 
     [1, 0, 0], 
     [1, 1, 1]]), 
    values=array([ 0.1  , 0.2  , 0.30000001, 0.40000001], 
     dtype=float32), 
    dense_shape=array([2, 3, 2])) 

注意,組合SparseTensor的形狀是原始批量維度,後面是每個其他維度的批次最大值離子。

+0

謝謝你的描述性解釋和片段。這很好。 – user7542570