MXNet快速开始之Manipulate data with ndarray

mxnet的NDArray类似于NumPy的多维数组

Get started

首先,import ndarray package (nd is a shorter alias) from MXNet.

# If you haven't installed MXNet yet, you can uncomment the following line to
# install the latest stable release
# !pip install -U mxnet

from mxnet import nd

create a 2D array (also called a matrix) with values from two sets of numbers: 1, 2, 3 and 4, 5, 6.

nd.array(((1,2,3),(5,6,7)))

输出:
[[1. 2. 3.]
 [5. 6. 7.]]
<NDArray 2x3 @cpu(0)>

生成2行3列的全1矩阵

x = nd.ones((2,3))
x

输出:
[[1. 1. 1.]
 [1. 1. 1.]]
<NDArray 2x3 @cpu(0)>

生成随机矩阵(此处的示例中生成的随机数在-1到1之间)

y = nd.random.uniform(-1,1,(2,3))
y
输出:
[[0.09762704 0.18568921 0.43037868]
 [0.6885315  0.20552671 0.71589124]]
<NDArray 2x3 @cpu(0)>

生成包含指定值的矩阵(示例中为2.0)

x = nd.full((2,3), 2.0)
x
输出:
[[2. 2. 2.]
 [2. 2. 2.]]
<NDArray 2x3 @cpu(0)>

查看ndarray的shape,size,dtype

(x.shape, x.size, x.dtype)
输出:
((2, 3), 6, numpy.float32)

Operations

乘法

x * y

Exponentiation:(将ndarray中的每个值都用e^(这个值)替代)

y.exp()

转置及矩阵点乘

nd.dot(x, y.T)

Indexing

y[1,2]
输出:
[0.71589124]
<NDArray 1 @cpu(0)>

读取第二到第四列(索引越界了也可以,返回的只包含存在的维度)

y[:,1:3]
输出:
[[0.18568921 0.43037868]
 [0.20552671 0.71589124]]
<NDArray 2x2 @cpu(0)>

将第二到第四列赋值为2(索引越界了也可以,返回的只包含存在的维度)

y[:,1:3] = 2
y
输出:
[[0.09762704 2.         2.        ]
 [0.6885315  2.         2.        ]]
<NDArray 2x3 @cpu(0)>
y[1:2,0:2] = 4
y
输出:
[[0.09762704 2.         2.        ]
 [4.         4.         2.        ]]
<NDArray 2x3 @cpu(0)>

Converting between MXNet NDArray and NumPy

NDArray到NumPy

a = x.asnumpy()
(type(a), a)
输出:
(numpy.ndarray, array([[2., 2., 2.],
        [2., 2., 2.]], dtype=float32))

NumPy到NDArray

nd.array(a)
输出:

你可能感兴趣的:(MXNet)