如果我理解正確的話,當前輸入labels
看起來是這樣的:
[[4, 3, 1, 2, 5],
[2, 3, 4, 1, 0],
[1, 2, 3, 0, 0],
[5, 4, 0, 0, 0]]
中,我們有batch_size=4
,max_time=5
和labels_length=[5,4,3,2]
。
如果是這種情況,您可以使用與here相同的方法將其轉換爲SparseTensor
。因此,只要您總是填充零,就不需要使用labeles_length
。
import tensorflow as tf
labels = tf.Variable([[4, 3, 1, 2, 5],
[2, 3, 4, 1, 0],
[1, 2, 3, 0, 0],
[5, 4, 0, 0, 0]], tf.int32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
idx = tf.where(tf.not_equal(labels, 0))
sparse = tf.SparseTensor(idx, tf.gather_nd(labels, idx), labels.get_shape())
s = sess.run(sparse)
print s.indices
print s.values
print s.dense_shape
> [[0 0]
[0 1]
[0 2]
[0 3]
[0 4]
[1 0]
[1 1]
[1 2]
[1 3]
[2 0]
[2 1]
[2 2]
[3 0]
[3 1]]
> [4 3 1 2 5 2 3 4 1 1 2 3 5 4]
> [4 5]
爲了更好地理解稀疏張量(實際上它不是一個張量,但圍繞着三個張量的包裝),請參閱documentation。
當建立圖形時無法推斷標籤張量的形狀時,能否請您針對特定情況更新您的答案?例如'形狀= [?,?]',這會拋出:'ValueError:無法將部分已知的TensorShape轉換爲張量:(?,?)' – George
此外,您的解決方案比[ctc_labels_dense_to_sparse] ://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/contrib/keras/python/keras/backend.py#L3836)來自我在這裏發佈後發現的Keras,只有一行來計算索引。在我看來,結果與這兩種解決方案看起來完全相同。 – George
如果張量形狀是動態的,則使用'tf.shape(labels,out_type = tf.int32)而不是labels.get_shape()'。或者有一個'get_shape' [這裏]的更一般的片段(https://github.com/vahidk/EffectiveTensorflow#get-shape-)。 – greeness