2

I have a two 1 dimensional arrays, a such that np.shape(a) == (n,) and b such that np.shape(b) == (m,).

I want to make a (3rd order) tensor c such that np.shape(c) == (n,n,m,)by doing c = np.outer(np.outer(a,a),b).

But when I do this, I get:

>> np.shape(c) 

(n*n,m)   

which is just a rectangular matrix. How can I make a 3D tensor like I want?

3
  • np.outer flattens the input as described in the docs... are you maybe searching for np.kron? Commented May 19, 2015 at 11:32
  • can you give an example of what you want? Commented May 19, 2015 at 11:35
  • So it appears, through experimentation in ipython, that np.kron(b,np.kron(a,a)).reshape(m,n,n) gives what I wanted, although indeces are reversed. But that's clean so I'll use this I think. Commented May 19, 2015 at 11:41

1 Answer 1

3

You could perhaps use np.multiply.outer instead of np.outer to get the required outer product:

>>> a = np.arange(4)
>>> b = np.ones(5)
>>> mo = np.multiply.outer

Then we have:

>>> mo(mo(a, a), b).shape
(4, 4, 5)

A better way could be to use np.einsum (this avoids creating intermediate arrays):

>>> c = np.einsum('i,j,k->ijk', a, a, b)
>>> c.shape
(4, 4, 5)
Sign up to request clarification or add additional context in comments.

1 Comment

I like this better than using np.kron as it retains the shape information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.