0

Assume I have a matrix of matrices, which is an order-4 tensor. What's the best way to apply the same operation to all the submatrices, similar to Map in Mathematica?

#!/usr/bin/python3
from pylab import *
t=random( (8,8,4,4) )
#t2=my_map(det,t)
#then shape(t2) becomes (8,8)

EDIT
Sorry for the bad English, since it's not my native one.

I tried numpy.linalg.det, but it doesn't seem to cope well with 3D or 4D tensors:

>>> import numpy as np
>>> a=np.random.rand(8,8,4,4)
>>> np.linalg.det(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/numpy/linalg/linalg.py", line 1703, in det
sign, logdet = slogdet(a)
File "/usr/lib/python3/dist-packages/numpy/linalg/linalg.py", line 1645, in slogdet
_assertRank2(a)
File "/usr/lib/python3/dist-packages/numpy/linalg/linalg.py", line 155, in _assertRank2
'two-dimensional' % len(a.shape))
numpy.linalg.linalg.LinAlgError: 4-dimensional array given. Array must be two-dimensional

EDIT2 (Solved) The problem is older numpy version (<1.8) doesn't support inner loop in numpy.linalg.det, updating to numpy 1.8 solves the problem.

2 Answers 2

1

numpy 1.8 has some gufunc that can do this in C loop:

for example, numpy.linalg.det() is a gufunc:

import numpy as np
a = np.random.rand(8,8,4,4)
np.linalg.det(a)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! But I got error message: numpy.linalg.linalg.LinAlgError: 4-dimensional array given. Array must be two-dimensional
Are you using numpy 1.8?
1

First check the documentation for the operation that you intend to use. Many have a way of specifying which axis to operate on (np.sum). Others specify which axes they use (e.g. np.dot).

For np.linalg.det the documentation includes:

a : (..., M, M) array_like Input array to compute determinants for.

So np.linalg.det(t) returns an (8,8) array, having calculated each det using the last 2 dimensions.

While it is possible to iterate on dimensions (the first is the default), it is better to write a function that makes use of numpy operations that use the whole array.

Comments

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.