2016-02-22 167 views
3

假设我有张量流中的两个张量,第一维表示批处理中训练样例的索引,其他维度表示一些数据矩阵向量。例如张量流元素矩阵乘法

vector_batch = tf.ones([64, 50]) 
matrix_batch = tf.ones([64, 50, 50]) 

我很好奇什么最习惯的方法来执行向量*矩阵乘法中,对于每个对矢量,共享沿着第一维度中的索引矩阵的。

阿卡一个最惯用的方式来写:

result = tf.empty([64,50]) 
for i in range(64): 
    result[i,:] = tf.matmul(vector_batch[i,:], matrix_batch[i,:,:]) 

什么是组织输入向量的形状,以使这个过程简单/清洁尽可能最好的方式是什么?

回答

6

可能是最惯用的方式做到这一点是使用tf.batch_matmul()运营商(连同tf.expand_dims()tf.squeeze()

vector_batch = tf.placeholder(tf.float32, shape=[64, 50]) 
matrix_batch = tf.placeholder(tf.float32, shape=[64, 50, 50]) 

vector_batch_as_matrices = tf.expand_dims(vector_batch, 1) 
# vector_batch_as_matrices.get_shape() ==> [64, 1, 50] 

result = tf.batch_matmul(vector_batch_as_matrices, matrix_batch) 
# result.get_shape() ==> [64, 1, 50] 

result = tf.squeeze(result, [1]) 
# result.get_shape() ==> [64, 50] 
+0

这正是我一直在寻找,谢谢 – Taaam

+1

嗯'tf.batch_matmul'不在tf 1中存在 - 什么是等效代码?普通matmul? –