在scipy中使用tracedot执行外积系列

4 投票
2 回答
1336 浏览
提问于 2025-04-16 12:33

在Python中,如果你想对两个向量进行外积运算,可以使用outer函数,或者像这样简单地用dot:

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

现在问题来了,假设我有一个向量列表(或者两个列表……),我想计算所有的外积,生成一个个方阵。我该怎么简单地做到这一点呢?我觉得tensordot可以做到这一点,但具体怎么做呢?

2 个回答

1

其实,pv 提供的答案是不对的,因为得到的 xy 数组的形状会是 (100,3,3)。

正确的广播方式是这样的:

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,:] 

现在得到的 xy 数组的形状是 (100,100,3,3),里面包含了 x 和 y 中所有 3 维向量的叉乘结果:

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")

没有输出哦 :)

5

计算外积的第三种方法(也是最简单的一种)是通过广播来实现的。

一些三维向量(行向量):

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

外积:

from numpy import newaxis
xy = x[:,:,newaxis] * y[:,newaxis,:]

# 10th matrix
print xy[10]
print np.outer(x[10,:], y[10,:])

撰写回答