這是可能與位瓷磚和重塑:
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的形狀是原始批量維度,後面是每個其他維度的批次最大值離子。
你有沒有考慮過[sparse_merge](https://www.tensorflow.org/api_docs/python/sparse_ops/conversion#sparse_merge)? –
我出院的張量是密集的張量。 'sparse_merge'似乎是什麼輸入稀疏張量。 'sp_ids:具有int32或int64類型的值屬性的SparseTensor。 sp_values:任何類型的ASparseTensor.' – user7542570
對,我很愚蠢。我已經把答案放在一起。 –