如何填充兩個相同形狀的張量,使它們都具有相同的大小?我目前收到以下代碼的錯誤(我不能for在圖形模式下使用回圈):
def match_size(self, x, y):
d = tf.maximum(tf.subtract(y.shape, x.shape), 0)
x = tf.pad(x, [[0, i] for i in d])
d = tf.maximum(tf.subtract(x.shape, y.shape), 0)
y = tf.pad(y, [[0, i] for i in d])
return x, y
此代碼將在 Keras 模型的call方法中運行,因為在執行的各個階段x,y張量的特征大小(形狀的最后暗淡)會有所不同(batch, horizon, feature)(即,我無法提前決定在build什么大小/形狀期間將會)。
以下是預期的輸入/輸出示例:
x = (10, 4, 4), y = (10, 4, 2)~> x = (10, 4, 4), y = (10, 4, 4)
x = (10, 4, 2), y = (10, 4, 4)~> x = (10, 4, 4), y = (10, 4, 4)
...它也應該適用于所有維度:
x = (10, 3, 2), y = (10, 4, 1)~>x = (10, 4, 2), y = (10, 4, 2)
uj5u.com熱心網友回復:
使用ragged.stack:
def match_size(x, y):
new_axis = tf.argsort(tf.abs(tf.constant(x.shape) - tf.constant(y.shape)), direction='DESCENDING')
x_y = tf.ragged.stack([tf.transpose(x, new_axis),tf.transpose(y, new_axis)])
x,y = x_y.to_tensor(0.)
return tf.transpose(x, tf.argsort(new_axis)), tf.transpose(y, tf.argsort(new_axis))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/526968.html
標籤:Python张量流填充
上一篇:了解Keras約束
下一篇:張量流中的前向插補
