在MxNet中,NDArray是所有数学运算的核心数据结构,与Numpy中的ndarray相似。与numpy相比,MxNet中的NDArray有以下的优点:
在Mxnet中,NDArray实质上指的是mx.nd.array,并且有以下几种常用的属性:
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}
c = np.arange(15).reshape(3,5)
# create a 2-dimensional array from a numpy.ndarray object
a = mx.nd.array(c)
# 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)
# 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))
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()))
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()
a = mx.nd.array(np.arange(6).reshape(6,1))
b = a.broadcast_to((6,4)) #得到是6*4矩阵
b.asnumpy()
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