简体   繁体   English

theano:两个矩阵之间的按行外积

[英]theano: row-wise outer product between two matrices

I'm trying to compute the row-wise outer-product between two matrices in theano, without using scan. 我试图不使用扫描来计算theano中两个矩阵之间的按行外积。 I can do this in numpy by using einsum, which isn't available in theano. 我可以使用einsum在numpy中完成此操作,而theano则不可用。

A = np.array([[1,1,1],[2,2,2]])
B = np.array([[3,3,3,3],[4,4,4,4]])
print np.einsum('xi,xj->xij', A, B)
[[[3 3 3 3]
  [3 3 3 3]
  [3 3 3 3]]

 [[8 8 8 8]
  [8 8 8 8]
  [8 8 8 8]]]

This should be doable using some reshaping: Many of the simple einsum operations boil down to that. 这可以通过重塑来实现:许多简单的einsum操作可以归结为这一点。 The complicated ones don't. 复杂的没有。

import theano
import theano.tensor as T
import numpy as np

a = np.array([[1,1,1],[2,2,2]]).astype('float32')
b = np.array([[3,3,3,3],[4,4,4,4]]).astype('float32')

A = T.fmatrix()
B = T.fmatrix()

C = A[:, :, np.newaxis] * B[:, np.newaxis, :]

print C.eval({A:a, B:b})

results in 结果是

[[[ 3.  3.  3., 3.]
  [ 3.  3.  3., 3.]
  [ 3.  3.  3.. 3.]]

 [[ 8.  8.  8., 8.]
  [ 8.  8.  8., 8.]
  [ 8.  8.  8., 8.]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM