2016-02-04 139 views
2

我有以下兩個張量:TensorFlow批次外積

x, with shape [U, N] 
y, with shape [N, V] 

欲執行批外積:我想由每個元件在所述第一相乘的每個元素中的x第一列行y得到形狀的張量[U, V],然後x的第二列由第二行y等等。最終張量的形狀應該是[N, U, V],其中N是批量大小。

在TensorFlow中有什麼簡單的方法來實現這個嗎?我試圖用batch_matmul()沒有成功。

回答

4

下面的工作,使用tf.batch_matmul()

print x.get_shape() # ==> [U, N] 
print y.get_shape() # ==> [N, V] 

x_transposed = tf.transpose(x) 
print x_transposed.get_shape() # ==> [N, U] 

x_transposed_as_matrix_batch = tf.expand_dims(x_transposed, 2) 
print x_transposed_as_matrix_batch.get_shape() # ==> [N, U, 1] 

y_as_matrix_batch = tf.expand_dims(y, 1) 
print y_as_matrix_batch.get_shape() # ==> [N, 1, V] 

result = tf.batch_matmul(x_transposed_as_matrix_batch, y_as_matrix_batch) 
print result.get_shape() # ==> [N, U, V] 
+0

謝謝,這有助於! – njk