Home > OS >  Why did I get an warning when calculating matrix multiplication of a grid and a vector in Python?
Why did I get an warning when calculating matrix multiplication of a grid and a vector in Python?

Time:06-10

I have the following code of calculating the multiplication of a grid and a vector:

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

The warning was:

<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.

Why did the warning happen and how should I remove it in a good way?

CodePudding user response:

The reason for the warning is that Grid is a list of differently shaped arrays ((512, 1, 1), (1, 512, 1), and (1, 1, 256)). You can silence the warning by specifying the dtype as object:

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

The result is a (512, 512, 256) shaped 3D array.

  • Related