To perform an outer product between two vectors in Python (scipy/numpy) you can use the outer function, or you can simply use dot 开发者_运维百科like this:
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 the outer products, creating a list of square matrices. How do I do that easily? I believe tensordot is able to do that, but how?
The third (and easiest to generalize) way to compute outer products is via broadcasting.
Some 3-vectors (vectors on rows):
import numpy as np
x = np.random.randn(100, 3)
y = np.random.randn(100, 3)
Outer product:
from numpy import newaxis
xy = x[:,:,newaxis] * y[:,newaxis,:]
# 10th matrix
print xy[10]
print np.outer(x[10,:], y[10,:])
Actually the answer provided by pv. is not correct, as the resulting xy array would have shape (100,3,3). The correct broadcasting is the following:
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 xy array is now of shape (100,100,3,3) and contains cross products of all couples of 3-vectors in 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")
gives no output :)
精彩评论