我一直在寻找一种简洁的方法来创建一个矩阵,将相同的函数应用于不同大小的iterables中的元素。一个是m=3,一个是n=4
a = range(3)
b = range(4)
这只是一个最简单的例子,我可以用numpy向量来做同样的事情。你知道吗
我想用这种方式填充矩阵:
yawn = np.zeros((len(a), len(b)), dtype='float')
meh = lambda x, y: np.exp(x + y) / (1 + np.exp(x + y))
for i in a:
for j in b:
yawn[i,j] = meh(i,j)
预期结果确实是:
array([[ 0.5 , 0.73105858, 0.88079708, 0.95257413],
[ 0.73105858, 0.88079708, 0.95257413, 0.98201379],
[ 0.88079708, 0.95257413, 0.98201379, 0.99330715]])
我试着用np.vectorize()或np.fromfunction()之类的东西,我已经接近了:
meh_vec = np.vectorize(meh)
meh_vec(a, 3)
array([ 0.95257413, 0.98201379, 0.99330715])
但我能想出来是否有办法做到这一点:
meh_vec(a, b)
不会导致ValueError:
ValueError: operands could not be broadcast together with shapes (3,) (4,)
而且我读到:
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
有没有比for循环更紧凑、更快的解决方案?你知道吗
将这些数组转换为
open
数组,这些数组可以针对2D
数组进行广播,而np.ix_
-或者,更明确地说,我们可以在输入的数组版本上用
None/np.newaxis
手动扩展维度-为了进一步优化,我们可能需要存储
np.exp(a[:,None] + b)
并重用分区。而且,a[:,None] + b
可以被重写为np.add.outer(a,b)
,因为这基本上是一个外部加法。你知道吗相关问题 更多 >
编程相关推荐