mxnet.npx.set_np

set_np(shape=True, array=True, dtype=False)

Setting NumPy shape and array semantics at the same time. It is required to keep NumPy shape semantics active while activating NumPy array semantics. Deactivating NumPy shape semantics while NumPy array semantics is still active is not allowed. It is highly recommended to set these two flags to True at the same time to fully enable NumPy-like behaviors. Please refer to the Examples section for a better understanding.

Parameters
  • shape (bool) – A boolean value indicating whether the NumPy-shape semantics should be turned on or off. When this flag is set to True, zero-size and zero-dim shapes are all valid shapes in shape inference process, instead of treated as unknown shapes in legacy mode.

  • array (bool) – A boolean value indicating whether the NumPy-array semantics should be turned on or off. When this flag is set to True, it enables Gluon code flow to use or generate mxnet.numpy.ndarray`s instead of `mxnet.ndarray.NDArray. For example, a Block would create parameters of type mxnet.numpy.ndarray.

  • dtype (bool) – A boolean value indicating whether the NumPy-dtype semantics should be turned on or off. When this flag is set to True, default dtype is float64. When this flag is set to False, default dtype is float32.

Examples

>>> import mxnet as mx

Creating zero-dim ndarray in legacy mode would fail at shape inference.

>>> mx.nd.ones(shape=())
mxnet.base.MXNetError: Operator _ones inferring shapes failed.
>>> mx.nd.ones(shape=(2, 0, 3))
mxnet.base.MXNetError: Operator _ones inferring shapes failed.

In legacy mode, Gluon layers would create parameters and outputs of type mx.nd.NDArray.

>>> from mxnet.gluon import nn
>>> dense = nn.Dense(2)
>>> dense.initialize()
>>> dense(mx.nd.ones(shape=(3, 2)))
[[0.01983214 0.07832371]
 [0.01983214 0.07832371]
 [0.01983214 0.07832371]]
<NDArray 3x2 @cpu(0)>
>>> [p.data() for p in dense.collect_params().values()]
[
[[0.0068339  0.01299825]
 [0.0301265  0.04819721]]
<NDArray 2x2 @cpu(0)>,
[0. 0.]
<NDArray 2 @cpu(0)>]

When the shape flag is True, both shape inferences are successful.

>>> from mxnet import np, npx
>>> npx.set_np()  # this is required to activate NumPy-like behaviors
>>> np.ones(shape=())
array(1.)
>>> np.ones(shape=(2, 0, 3))
array([], shape=(2, 0, 3))

When the array flag is True, Gluon layers would create parameters and outputs of type mx.np.ndarray.

>>> dense = nn.Dense(2)
>>> dense.initialize()
>>> dense(np.ones(shape=(3, 2)))
array([[0.01983214, 0.07832371],
       [0.01983214, 0.07832371],
       [0.01983214, 0.07832371]])
>>> [p.data() for p in dense.collect_params().values()]
[array([[0.0068339 , 0.01299825],
       [0.0301265 , 0.04819721]]), array([0., 0.])]
>>> npx.set_np(dtype=True)
>>> np.ones(shape=()).dtype
dtype('float64')