【发布时间】:2017-10-11 05:24:48
【问题描述】:
我正在用 numpy 数组做一个小实验,我遇到了以下问题。我正在尝试找到一种方法来映射一个函数,该函数将输入数组作为矩阵的输入,以便该函数应用于两个或多个矩阵的成对元素,其中这些元素是数组。
import numpy as np
x = np.random.random_integers(100, size=(5,4))
y = np.random.random_integers(100, size=(5,4))
print(x); print(y)
[[17 84 60 56]
[58 71 50 90]
[80 25 43 55]
[18 25 77 25]
[62 49 42 11]]
[[ 9 51 83 58]
[34 63 26 32]
[27 54 63 80]
[29 42 10 6]
[53 52 45 87]]
# np.dot(x,y) fails
v = np.vectorize(np.dot)
z = v(x,y)
print(z)
[[ 153 4284 4980 3248]
[1972 4473 1300 2880]
[2160 1350 2709 4400]
[ 522 1050 770 150]
[3286 2548 1890 957]] # this is wrong
np.sum(z[0]) == np.dot(x[0], y[0]) # prints True
# the vectorized dot function was applied over individual elements at the "bottom-most"
# (second) dimension when instead it should be applied to the array elements
# at the first dimension
# I could instead use list comprehension
z = [np.dot(a, b) for a, b in zip(x,y)]
print(z)
[12665, 10625, 10619, 2492, 8681]
# this would be a correct mapping of the dot function over the matrices x and y
列表推导式的问题在于我担心它们效率低下,因为它们是 Python 功能而不是 Numpy 功能。
【问题讨论】:
-
vectorize是 Python 级别的循环;它还将标量提供给您的函数,而不是数组。我知道在不阅读文档的情况下使用它很诱人,但它会为您节省一些错误的开始。