为什么numpy允许你添加不同大小的数组?

ren*_*ato 5 python arrays numpy

当你做类似的事情时,为什么numpy不会抛出错误

np.ones((5,5)) + np.ones(5)
Run Code Online (Sandbox Code Playgroud)

这种添加在线性代数中没有明确定义,它只花了我几个小时来追踪一个归结为这个的错误

M4r*_*ini 4

np.ones((5,5)) + np.ones(5)
np.ones((5,5)) + np.ones(4) <- This would give a error.
Run Code Online (Sandbox Code Playgroud)

由于 np.ones(5) 适合每行的大小,因此它将按元素添加到每行。

这就是 numpy 的工作原理。I 不是线性代数模块。

这是一个关于如何做到这一点的简短示例,这确实需要扩展,具有更多的逻辑和智慧。只是一个概念证明。

import numpy as np

class myMatrixClass(np.ndarray):
    def __add__(self,val):
        if (hasattr(val, '__iter__') and self.shape != val.shape):
            print "not valid addition!"
        else:
            return super(myMatrixClass, self).__add__(val)

In [33]: A = myMatrixClass( shape=(5,5))

In [34]: A[:] = 1

In [35]: B = A + 1

In [36]: B
Out[36]:
myMatrixClass([[ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.]])

In [37]: C = A + np.ones(5)
not valid addition!
Run Code Online (Sandbox Code Playgroud)

  • 可视化逐元素加法的一个好方法是:`np.ones((5,5)) + np.arange(5)` (3认同)