MxNet 学习笔记(1):MxNet中的NDArray

NDArray

在MxNet中,NDArray是所有数学运算的核心数据结构,与Numpy中的ndarray相似。与numpy相比,MxNet中的NDArray有以下的优点:

  1. 对平台通用:在CPU GPU下都兼容
  2. 可以自动地并行化

NDArray的创建

在Mxnet中,NDArray实质上指的是mx.nd.array,并且有以下几种常用的属性:

  • ndarray.shape: The dimensions of the array. It is a tuple of integers
    indicating the length of the array along each axis. For a matrix with
    n rows and m columns, its shape will be (n, m).
  • ndarray.dtype: A numpy type object describing the type of its elements.
  • ndarray.size: the total number of components in the array - equal to the product of the components of its shape
  • ndarray.context: The device on which this array is stored, e.g. cpu() or gpu(1).

通过常量来创建:

import mxnet as mx
# create a 1-dimensional array with a python list
a = mx.nd.array([1,2,3])
# create a 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}

通过numpy.ndarray构造:

c = np.arange(15).reshape(3,5)
# create a 2-dimensional array from a numpy.ndarray object
a = mx.nd.array(c)

创建时指定特定的数据类型(如果不指定,默认为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)

若干种初始化NDArray的方法

# 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))

打印NDArray

a = mx.nd.array(([1,2,3],[4,5,6]))
# or a = mx.nd.array(((1,2,3),(4,5,6)))
print a.asnumpy() #一定要记得asnumpy是一个方法

基本运算

两个NDArray之间的加减乘除(+-*/),以及递增递减(+=,-=)指的是元素与元素之间运算,而实现矩阵乘法需要用dot():

a = mx.nd.arange(4).reshape((2,2))
c = mx.nd.dot(a,a)
print("b: %s, \n c: %s" % (b.asnumpy(), c.asnumpy()))

NDArray的访问

  • 访问二维矩阵中的元素可以直接用[m][n]
  • 将取出若干行或者给若干行赋值可以用a[m:n]的方式:
a = mx.nd.array(np.arange(6).reshape(3,2))
a[1:2] = 1
a[:].asnumpy()
  • 对某一个维度进行操作:
d = mx.nd.slice_axis(a, axis=1, begin=1, end=2)
d.asnumpy()

维度操作

  • reshape:跟大多数矩阵库一样
  • concat:将两个矩阵拼接在一起(沿着第一个轴,也就是2*3与2*3的矩阵拼接得到的是2*6矩阵)
  • 矩阵扩充(在一些维度不相等的加法和乘法上,会自动调用):
a = mx.nd.array(np.arange(6).reshape(6,1))
b = a.broadcast_to((6,4))  #得到是6*4矩阵
b.asnumpy()

深拷贝 V.S. 浅拷贝

  • 当直接用=的时候,是浅拷贝
  • 用b = a.copy()的时候,是深拷贝
  • 判断两个变量所指向的内存是否相等,直接用is
  • 当被拷贝的变量中本身有内存空间,不想额外重新分配,可以用[]
b = mx.nd.ones(a.shape) #b是独立的空间
c = b  #c指向b
c[:] = a #c的内容被赋为a,但内存空间指向b
d = b
a.copyto(d) #d的内容被赋为a,但内存空间指向b
(c is b, d is b)  # Both will be True

你可能感兴趣的:(机器学习,MxNet)