[英]How to pad a irregular shape tensor in tensorflow (pure TF way)?
test_tensor = [[2], [1, 2, 3], [4, 5]] # irregular shape
# dose there have a tf (better, and faster?) function to pad this tensor to a dense tensor with a defult value?
# like this: test_tensor ==> dense tensor:[[2, -1, -1],[1, 2, 3], [4, 5, -1]]
PS。 請不要使用純python和numpy
因為我需要將此操作添加到我的TF模型圖中,所以也許需要用純TF方式完成該操作?
我假設您的起始張量的類型為SparseTensor。 (我認為不可能具有“不規則形狀”的密集張量。如果類型甚至不是張量,則不需要“純TF方式”)
使用以下內容:
dense = tf.sparse_tensor_to_dense(sparse_tensor_input, default_value=-1)
https://www.tensorflow.org/api_docs/python/tf/sparse_tensor_to_dense
如果您希望密集張量的形狀與輸入稀疏張量的形狀不同,則可以在調用此函數之前更改后者的形狀,或者使用較低級別的函數https://www.tensorflow.org/api_docs/python / tf / sparse_to_dense 。
最近,我遇到了同樣的問題,並且我做了一點技巧(即使有人發表了將近一年的帖子,也可能有人遇到了同樣的問題)。
首先,TensorFlow無法將該數組轉換為密集張量,因此我將數組連接為字符串列表,就像a = ['2','1,2,3','4,5']
然后使用純TF代碼分割此字符串,這是簡單的代碼:
def pad_length(sequence, limited_len):
seq_sparse = tf.string_split(sequence, ',')
seq_dense = tf.sparse_to_dense(
seq_sparse.indices, seq_sparse.dense_shape, tf.cast(tf.string_to_number(seq_sparse.values), tf.int32)
)
seq_slice = tf.strided_slice(seq_dense, [0, 0], [tf.shape(sequence)[0], limited_len])
pad_dense = tf.pad(seq_slice, paddings=[[0, 0], [0, limited_len - tf.shape(seq_slice)[1]]])
return pad_dense
a = ['2','1,2,3','4,5']
a = tf.convert_to_tensor(a)
b = pad_length(a, 3)
sess=tf.Ssssion()
sess.run(b)
"""
b => array([
[2, 0, 0],
[1, 2, 3],
[4, 5, 0]
], dtype=int32)
"""
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.