我試圖弄清楚如何基于對二進制數“1”值的連續掩碼進行磁區,將我的順序資料張量分成多個部分。
我已經閱讀了官方檔案。但是,我找不到任何可以輕松處理此問題的功能。在python中有什么有用的方法嗎?
我嘗試過使用“tf.ragged.boolean_mask”,但它似乎不適合我的情況。
我解釋的可視化示例是:
輸入:
# both are tensors, NOT data.
data_tensor = ([3,5,6,2,6,1,3,9,5])
mask_tensor = ([0,1,1,1,0,0,1,1,0])
預期輸出:
output_tensor = ([[3],[5,6,2],[6,1],[3,9],[5]])
謝謝你。
uj5u.com熱心網友回復:
我最近在@AloneTogether的這個答案中發現了一種非常干凈的方法:
import tensorflow as tf
data_tensor = tf.constant([3,5,6,2,6,1,3,9,5])
mask_tensor = tf.constant([0,1,1,1,0,0,1,1,0])
# Index where the mask changes.
change_idx = tf.concat([tf.where(mask_tensor[:-1] != mask_tensor[1:])[:, 0], [tf.shape(mask_tensor)[0]-1]], axis=0)
# Ranges of indices to gather.
ragged_idx = tf.ragged.range(tf.concat([[0], change_idx[:-1] 1], axis=0), change_idx 1)
# Gather ranges into ragged tensor.
output_tensor = tf.gather(data_tensor, ragged_idx)
print(output_tensor)
<tf.RaggedTensor [[3], [5, 6, 2], [6, 1], [3, 9], [5]]>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479253.html
