用可数函数填充numpy矩阵

2024-09-25 16:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找一种简洁的方法来创建一个矩阵,将相同的函数应用于不同大小的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循环更紧凑、更快的解决方案?你知道吗


Tags: theinforlenisnpnotrange
1条回答
网友
1楼 · 发布于 2024-09-25 16:19:34

将这些数组转换为open数组,这些数组可以针对2D数组进行广播,而np.ix_-

In [57]: x,y = np.ix_(a,b)

In [58]: np.exp(x + y) / (1 + np.exp(x + y))
Out[58]: 
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]])

或者,更明确地说,我们可以在输入的数组版本上用None/np.newaxis手动扩展维度-

In [64]: a = np.arange(3)
    ...: b = np.arange(4)

In [65]: np.exp(a[:,None] + b) / (1 + np.exp(a[:,None] + b))
Out[65]: 
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.exp(a[:,None] + b)并重用分区。而且,a[:,None] + b可以被重写为np.add.outer(a,b),因为这基本上是一个外部加法。你知道吗

相关问题 更多 >