NDArray指南

作者: yfmei | 来源:发表于2017-04-11 16:28 被阅读0次

    在MXNET中最主要的一个对象就是由mxnet.ndarray或者mxnet.nd(缩写)包提供的多维数组。如果你熟悉python的科学计算包Numpy,那么你会发现mxnet.ndarray和numpy.ndarry在很多方面都很相似。

    基础
    一个多维数组是一个具有相同类型的数表。举个例子,3维空间中的一个点的坐标[1,2,3]是一个长度为3的一维数组。下图展示了一个二维数组。第一维的长度是2,第二维的长度是3

    [[0, 1, 2]
     [3, 4, 5]]
    

    这个数组的类型就叫做NDArray。一个NDArray对象的重要属性:

    • ndarray.shape 数组的维度。它是一个整数组成的tuple,表示各维度的长度。对于一个n行m列的矩阵,它的shape就是(n,m)。
    • ndarry.dtype 一个用来描述元素类型的numpy对象。
    • ndarray.size 数组中数字的总数,也就是shape中的元素的乘积
    • ndarray.context 存储数组的设备。可以使cpu也可是i-th gpu

    创建数组
    创建数组可以有很多方式。举个例子,我们可以通过使用array函数,利用python中常规的list或者tuple中创建数组

    import mxnet as mx
    # create a 1-dimensional array with a python list
    a = mx.nd.array([1,2,3])
    # create 2-dimensional array with a nested python list
    b = mx.nd.array([[1,2,3],[2,3,4]])
    {'a.shape':a.shape,'b.shape':b.shape}
    
    {'a.shape': (3L,), 'b.shape': (2L, 3L)}
    

    也可以使用使用 numpy.ndarray对象

    import numpy as np
    import math
    c = np.arrange(15).reshape(3,5)
    # create a 2-dimensional array from a numpy.ndarray object
    a = mx.nd.array(c)
    {'a.shape':a.shape}
    
    {'a.shape':(3L,5L)}
    

    我们可以使用可选参数dtype来指定元素类型,它接受numpy类型。默认使用float32。

    # float32 is used in default
    a = mx.nd.array([1,2,3])
    # create an int32 array
    b = mx.nd.array([1,2,3],dtype=np.int32)
    # create a 16-bit float array
    c = mx.nd.array([1.2,2.3],dtype=np.float16)
    (a.dtype,b.dtype,c.dtype)
    
    (numpy.float32, numpy.int32, numpy.float16)
    

    如果我们只知道大小而不知道元素的值,有几个函数可以创建并初始化占位符内容

    # create a 2-dimensional array full of zeros with shape(2,3)
    a = mx.nd.zeros((2,3))
    # create a same shape array full of ones
    b = mx.nd.ones((2,3))
    # create a same shape array with all elements set to 7
    c = mx. nd.full((2,3),7)
    # create a same shape whose initial content is random and
    # depends on the state of the memory
    d = mx.nd.empty((2,3))
    

    打印数组
    为了能够打印,我们一般会使用asnumpy函数把NDArray转换成numpy.ndarray。Numpy使用下面的布局设计:

    • 从左到右打印最后一个维度
    • 从上到下打印倒数第二个维度
    • 剩下的也是从上到下打印,每片由一个空行隔开
    b = mx.nd.ones((2,3))
    b.asnumpy()
    
    array([[1.,1.,1.],
              [1.,1.,1.]],dtype=float32)
    

    基本操作
    在数组上使用算术运算符进行按元素操作。就会创建一个新的数组,并填充结果。

    a = mx.nd.ones((2,3))
    b = mx.nd.ones((2,3))
    # elementwise plus 按元素加
    c = a+b
    # elementwise minus 按元素减
    d = - c
    # elementwise pow and sin,and then transpose 按元素平方,在求sin,最后进行转置
    e = mx.nd.sin(c**2).T
    # elementwise max 按元素求最大
    f = mx.nd.maximum(a,c)
    f.asnumpy()
    
    array([[ 2.,  2.,  2.],
           [ 2.,  2.,  2.]], dtype=float32)
    

    和Numpy相似,*被用来做按元素乘积,而矩阵和矩阵的乘积使用dot

    a = mx.nd.ones((2,2))
    b = a * a
    c = mx.nd.dot(a,a)
    {'b':b.asnumpy(),'c':c.asnumpy()}
    
    {'b': array([[ 1.,  1.],
            [ 1.,  1.]], dtype=float32), 'c': array([[ 2.,  2.],
            [ 2.,  2.]], dtype=float32)}
    

    像 += 和 *= 这样的赋值运算符,用来修改已经存在的数组而不是创建新的

    a = mx.nd.ones((2,2))
    b = mx.nd.ones(a.shape)
    b += a
    b.asnumpy()
    

    索引和切片
    切片操作符[]作用在第一个维上

    a = mx.nd.array(np.arange(6).reshape(3,2))
    a[1:2] = 1 # 第2行开始,不取到第3行(我觉得意思是把第二行都改成1)
    #a[0:2] 第1行开始,不取到第3行
    a[:].asnumpy()
    
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 4.,  5.]], dtype=float32)
    

    我们也用slice_axis方法来切取一个特定的维度

    d = mx.nd.slice_axis(a,axis=1,begin=1,end=2) #切取第二维的数据,从第2列开始,不取到第3列(我觉得意思是只取第二列的数据)
    d.asnumpy()
    
    array([[ 1.],
           [ 1.],
           [ 5.]], dtype=float32)
    
    

    shape操作
    只要大小保持不变,数组的形状就可以改变

    a = mx.nd.array(np.arange(24))
    b = a.reshape((2,3,4))
    b.asnumpy()
    
    array([[[  0.,   1.,   2.,   3.],
            [  4.,   5.,   6.,   7.],
            [  8.,   9.,  10.,  11.]],
    
           [[ 12.,  13.,  14.,  15.],
            [ 16.,  17.,  18.,  19.],
            [ 20.,  21.,  22.,  23.]]], dtype=float32)
    

    方法concatenate沿着第一个维度堆叠多个数组。 (他们的形状必须相同)。

    a = mx.nd.ones((2,3))
    b = mx.nd.ones((2,3))*2
    c.asnumpy()
    
    array([[ 1.,  1.,  1.],
           [ 1.,  1.,  1.],
           [ 2.,  2.,  2.],
           [ 2.,  2.,  2.]], dtype=float32)
    
    

    降维
    我们可以将数组降成一个标量

    a = mx.nd.ones((2,3))
    b = mx.nd.sum(a)
    b.asnumpy()
    
    array([ 6.], dtype=float32)
    

    或者沿着特定的一个维度

    c = mx.nd.sum_axis(a,axis=1)#沿着第二维相加 即列相加
    c.asnumpy()
    
    array([ 3.,  3.], dtype=float32)
    

    广播
    我们可以通过复制来传播数组。下面的代码沿着第二维度传播:

    a  = mx.nd.array(np.arange(6).reshape(6,1))
    b = a.broadcast_to((6,2))
    b.asnumpy()
    
    array([[ 0.,  0.],
           [ 1.,  1.],
           [ 2.,  2.],
           [ 3.,  3.],
           [ 4.,  4.],
           [ 5.,  5.]], dtype=float32)
    

    相关文章

      网友评论

        本文标题:NDArray指南

        本文链接:https://www.haomeiwen.com/subject/gcayattx.html