Run a series of external products using tracedot in scipy

To do an external product between two vectors in Python (scipy / numpy), you can use an external function or just use a dot, for example:

In [76]: dot(rand(2,1), rand(1,2)) Out[76]: array([[ 0.43427387, 0.5700558 ], [ 0.19121408, 0.2509999 ]]) 

Now the question is: suppose I have a list of vectors (or two lists ...), and I want to calculate all external products by creating a list of square matrices. How can I do this easily? I believe tensdord can do this, but how?

+4
source share
2 answers

The third (and easiest to generalize) way of calculating external products is through broadcast.

Some 3-vectors (vectors on the lines):

 import numpy as np x = np.random.randn(100, 3) y = np.random.randn(100, 3) 

External product:

 from numpy import newaxis xy = x[:,:,newaxis] * y[:,newaxis,:] # 10th matrix print xy[10] print np.outer(x[10,:], y[10,:]) 
+5
source

Actually the answer provided by pv. incorrect, since the resulting xy array will have the form (100,3,3). Correct broadcasting:

 import numpy as np from numpy import newaxis x = np.random.randn(100, 3) y = np.random.randn(100, 3) xy = x[:,newaxis, :,newaxis] * y[newaxis,:,newaxis,:] 

The resulting array xy now has the form (100, 100, 3, 3) and contains the crossed products of all pairs of three-dimensional vectors with respect to x and y:

 for i,a in enumerate(x): for j,b in enumerate(y): if not np.alltrue(np.outer(a,b) == xy[i,j]): print("The code is wrong") 

does not display the result :)

+1
source

Source: https://habr.com/ru/post/1341357/


All Articles