【问题标题】:Why did I get an warning when calculating matrix multiplication of a grid and a vector in Python?为什么在 Python 中计算网格和向量的矩阵乘法时会收到警告?
【发布时间】:2022-06-11 00:36:52
【问题描述】:

我有以下计算网格和向量相乘的代码:

import numpy as np
Grid = np.ogrid[0:512, 0:512, 0:256]
Vec = np.array([1, 2, 3])
res = Vec @ Grid

警告是:

<stdin>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.

为什么会出现警告,我应该如何以一种好的方式将其删除?

【问题讨论】:

  • 警告中给出了原因(不推荐从不规则的嵌套序列创建 ndarray)和解决方法(指定 'dtype=object')。那么你的问题到底是什么。你不能按照建议做吗?
  • @Stef 我有一个上面定义的GridGrid 中节点的坐标为AA 是一个 (3, 512*512*256) 矩阵,我要计算Vec @ A
  • @Stef 在这种情况下如何指定'dtype=object'?
  • 你真的看过grid吗? grid.shape 是什么?

标签: numpy


【解决方案1】:

警告的原因是Grid 是不同形状数组的列表((512, 1, 1)(1, 512, 1)(1, 1, 256))。您可以通过将dtype 指定为object 来使警告静音:

Vec @ np.array(Grid, dtype=object)

结果是一个(512, 512, 256) 形状的 3D 数组。

【讨论】:

  • 我很想建议 mgrid 而不是 ogrid,但这会产生一个 (3,512,512,256) 数组,
【解决方案2】:

如前所述,ogrid 创建了一个形状不同的数组列表:

In [67]: o=np.ogrid[0:3,0:2,0:4]; [1,2,3]@np.array(o,object)
    ...: 
Out[67]: 
array([[[ 0,  3,  6,  9],
        [ 2,  5,  8, 11]],

       [[ 1,  4,  7, 10],
        [ 3,  6,  9, 12]],

       [[ 2,  5,  8, 11],
        [ 4,  7, 10, 13]]])

In [68]: o
Out[68]: 
[array([[[0]],
 
        [[1]],
 
        [[2]]]),
 array([[[0],
         [1]]]),
 array([[[0, 1, 2, 3]]])]

@ 适用于对象 dtype 数组,但使用较慢的代码,而不是快速的 BLAS。

mgrid 生成一个数组,可以通过适当的转置在@ 中使用(将乘积和维数放在最后:

In [69]: m=np.mgrid[0:3,0:2,0:4];
    ...: [1,2,3]@m.transpose(1,2,0,3)
Out[69]: 
array([[[ 0,  3,  6,  9],
        [ 2,  5,  8, 11]],

       [[ 1,  4,  7, 10],
        [ 3,  6,  9, 12]],

       [[ 2,  5,  8, 11],
        [ 4,  7, 10, 13]]])

In [71]: m.shape
Out[71]: (3, 3, 2, 4)

时间

In [72]: timeit o=np.ogrid[0:3,0:2,0:4]; [1,2,3]@np.array(o,object)
70.5 µs ± 5.04 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [73]: timeit m=np.mgrid[0:3,0:2,0:4]; [1,2,3]@m.transpose(1,2,0,3)
60.9 µs ± 77.1 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

分离出网格生成步骤,展示两种matmul的比较速度:

In [74]: %%timeit o=np.ogrid[0:3,0:2,0:4]
    ...: [1,2,3]@np.array(o,object)
28.3 µs ± 103 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [75]: %%timeit m=np.mgrid[0:3,0:2,0:4]; 
    ...: [1,2,3]@m.transpose(1,2,0,3)
8.35 µs ± 146 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多