gpt4 book ai didi

python - 广播和连接参差不齐的张量

转载 作者:行者123 更新时间:2023-12-04 11:30:04 24 4
gpt4 key购买 nike

我有一个尺寸参差不齐的张量 [BATCH_SIZE, TIME_STEPS, EMBEDDING_DIM] .我想用来自另一个形状张量的数据来增加最后一个轴 [BATCH_SIZE, AUG_DIM] .给定示例的每个时间步都增加了相同的值。
如果张量没有因变化而参差不齐 TIME_STEPS对于每个例子,我可以简单地用 tf.repeat 重塑第二个张量。然后使用 tf.concat :

import tensorflow as tf


# create data
# shape: [BATCH_SIZE, TIME_STEPS, EMBEDDING_DIM]
emb = tf.constant([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [0, 0, 0]]])
# shape: [BATCH_SIZE, 1, AUG_DIM]
aug = tf.constant([[[8]], [[9]]])

# concat
aug = tf.repeat(aug, emb.shape[1], axis=1)
emb_aug = tf.concat([emb, aug], axis=-1)
这在 emb 时不起作用自 emb.shape[1] 起破烂不堪未知且因示例而异:
# rag and remove padding
emb = tf.RaggedTensor.from_tensor(emb, padding=(0, 0, 0))

# reshape for augmentation - this doesn't work
aug = tf.repeat(aug, emb.shape[1], axis=1)

ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.


目标是创建一个参差不齐的张量 emb_aug看起来像这样:
<tf.RaggedTensor [[[1, 2, 3, 8], [4, 5, 6, 8]], [[1, 2, 3 ,9]]]>
有任何想法吗?

最佳答案

最简单的方法是使用 tf.RaggedTensor.to_tensor() 使不规则张量成为常规张量然后执行其余的解决方案。我假设你需要张量保持参差不齐。关键是要找到 row_lengths 不规则张量中的每个批次,然后使用此信息使您的增强张量不规则。
示例 :

import tensorflow as tf


# data
emb = tf.constant([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [0, 0, 0]]])
aug = tf.constant([[[8]], [[9]]])

# make embeddings ragged for testing
emb_r = tf.RaggedTensor.from_tensor(emb, padding=(0, 0, 0))

print(emb_r.shape)
# (2, None, 3)
这里我们将使用 row_lengths 的组合和 sequence_mask 创建一个新的参差不齐的张量。
# find the row lengths of the embeddings
rl = emb_r.row_lengths()

print(rl)
# tf.Tensor([2 1], shape=(2,), dtype=int64)

# find the biggest row length
max_rl = tf.math.reduce_max(rl)

print(max_rl)
# tf.Tensor(2, shape=(), dtype=int64)

# repeat the augmented data `max_rl` number of times
aug_t = tf.repeat(aug, repeats=max_rl, axis=1)

print(aug_t)
# tf.Tensor(
# [[[8]
# [8]]
#
# [[9]
# [9]]], shape=(2, 2, 1), dtype=int32)

# create a mask
msk = tf.sequence_mask(rl)

print(msk)
# tf.Tensor(
# [[ True True]
# [ True False]], shape=(2, 2), dtype=bool)
从这里我们可以使用 tf.ragged.boolean_mask 使增强数据参差不齐
# make the augmented data a ragged tensor
aug_r = tf.ragged.boolean_mask(aug_t, msk)
print(aug_r)
# <tf.RaggedTensor [[[8], [8]], [[9]]]>

# concatenate!
output = tf.concat([emb_r, aug_r], 2)
print(output)
# <tf.RaggedTensor [[[1, 2, 3, 8], [4, 5, 6, 8]], [[1, 2, 3, 9]]]>
您可以找到支持不规则张量的 tensorflow 方法列表 here

关于python - 广播和连接参差不齐的张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66605679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com