python - 使用 NumPy 广播的 View

标签 python numpy array-broadcasting

假设我有一个2D np.array X,并且我需要在一些中间计算中使用X[:, None, :];例如 np.sum(X[:, None, :] == Y[None, :, :], axis=2) 其中 Y 也是一个 2D np.array 。

此操作是否显式复制 XY 的内存以创建 X[:, None, :]Y [:, 无, :]?如果是这样,有没有办法通过使用 NumPy 中的 View 来避免这种复制?

最佳答案

X[:, None, :]Y[None, :, :] 已经是 View 。两个操作都是 NumPy basic slicing ,它总是生成一个 View 。

X[:, None, :] == Y[None, :, :] 将是一个更大的内存问题,因为它创建了一个非常大的 bool 数组。您可以通过根据 scipy.spatial.distance.cdist 重写计算来避免这种情况。在'hamming'模式下:

In [10]: x
Out[10]: 
array([[3, 0, 2, 2, 3],
       [3, 2, 1, 3, 2],
       [2, 2, 1, 1, 1]])
In [11]: y
Out[11]: 
array([[0, 0, 1, 2, 3],
       [2, 0, 0, 1, 1],
       [2, 0, 2, 3, 3],
       [2, 1, 1, 2, 1]])
In [12]: numpy.sum(x[:, None, :] == y[None, :, :], axis=2)
Out[12]: 
array([[3, 1, 3, 1],
       [1, 0, 1, 1],
       [1, 3, 1, 3]])
In [13]: 5 - 5*cdist(x, y, 'hamming') # 5 for the row length of x and y
Out[13]: 
array([[ 3.,  1.,  3.,  1.],
       [ 1.,  0.,  1.,  1.],
       [ 1.,  3.,  1.,  3.]])

在 scipy.spatial.distance 中没有计算非标准化汉明距离的选项,因此我们必须撤消标准化。

关于python - 使用 NumPy 广播的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289528/

相关文章:

python - 如何从位置参数增加文件名?

python - sqlalchemy.exc.OperationalError : Can't connect to mysql in docker

performance - 索引 numpy 记录数组非常慢

python - Pandas 迭代更新列值

python - 如何对二维数组进行平均?

python - 未知维度张量的逐元素乘法

python - 缩放/旋转成对平方欧氏距离的矢量化计算

php - 如何从 php 调用 python 脚本

用于生成正则表达式的 Python 库

python - Numpy 根据列表折叠列