📜  Apache MXNet- Python API ndarray(1)

📅  最后修改于: 2023-12-03 14:59:20.597000             🧑  作者: Mango

Apache MXNet- Python API ndarray

Apache MXNet is a flexible and efficient open-source deep learning framework that allows developers to build and train state-of-the-art deep learning models.

The Python API of Apache MXNet provides the ndarray module for efficient numerical computation with multi-dimensional arrays.

Creating ndarrays

ndarrays can be created with the mxnet.ndarray.array() function. You can pass a Python list, a NumPy array, or a scalar value to create an ndarray.

import mxnet as mx

# create an ndarray from a Python list
x = mx.ndarray.array([[1, 2], [3, 4]])

# create an ndarray from a NumPy array
import numpy as np
a = np.array([1, 2, 3])
y = mx.ndarray.array(a)

# create a scalar ndarray
z = mx.ndarray.array(1.0)
Arithmetic operations

ndarrays support a wide range of arithmetic operations, such as addition, subtraction, multiplication, and division. In MXNet, the mxnet.ndarray module provides a wide range of operators to perform these operations.

import mxnet as mx

x = mx.ndarray.array([1, 2, 3])
y = mx.ndarray.array([4, 5, 6])

# addition
z = x + y
print(z) # output: [5. 7. 9.]

# subtraction
z = x - y
print(z) # output: [-3. -3. -3.]

# multiplication
z = x * y
print(z) # output: [ 4. 10. 18.]

# division
z = x / y
print(z) # output: [0.25 0.4  0.5 ]
Broadcasting

Broadcasting is the automatic alignment of dimensions in arithmetic operations. When performing arithmetic operations on ndarrays with different shapes, the smaller array is broadcast to match the shape of the larger array.

import mxnet as mx

x = mx.ndarray.array([[1, 2], [3, 4]])
y = mx.ndarray.array([10, 20])

# broadcasting
z = x + y
print(z) # output: [[11. 22.], [13. 24.]]
Slicing

Slicing is the process of creating a sub-array from an ndarray by selecting a subset of its elements. You can slice ndarrays using the mxnet.ndarray.slice() function.

import mxnet as mx

x = mx.ndarray.array([[1, 2, 3], [4, 5, 6]])

# slicing
y = mx.ndarray.slice(x, begin=(0, 1), end=(2, 3))
print(y) # output: [[2. 3.], [5. 6.]]
Conclusion

The mxnet.ndarray module provides a powerful and efficient way to perform numerical computations with multi-dimensional arrays. With its support for broadcasting and slicing, you can easily manipulate ndarrays to perform complex deep learning operations.