Gluon学习03-基础数据类型Ndarray
目录,方便快速定位:
本机环境介绍:
系统:Linuxmint
Python版本:Python3
1.API介绍
MxNet版本:1.2.0
API地址:https://mxnet.incubator.apache.org/api/python/ndarray/ndarray.html
Ndarray在CPU/GPU上提供必要的张量操作,是一个多维的,固定大小的,同类型的矩阵.mxnet.ndarray与numpy.ndarray非常相似.
The NDArray class:
1.属性
shape/size/ndim/context/dtype
- import mxnet as mx
- from mxnet import nd
- import numpy as np
- #数据的形状
- 1, 2, 3, 4]) x = mx.nd.array([
- x.shape
- (4L,)
- 2, 3, 4)) y = mx.nd.zeros((
- y.shape
- (2L, 3L, 4L)
- #数据的多少
- import numpy as np
- 3, 5, 2)) x = mx.nd.zeros((
- x.size
- 30
- np.prod(x.shape)
- 30
- #数据的阶/秩
- 1, 2, 3, 4]) x = mx.nd.array([
- x.ndim
- 1
- 1, 2], [3, 4]]) x = mx.nd.array([[
- x.ndim
- 2
- #数据所在的设备
- 1, 2, 3, 4]) x = mx.nd.array([
- x.context
- cpu(0)
- type(x.context)
- 2,3), mx.gpu(0)) y = mx.nd.zeros((
- y.context
- gpu(0)
- #数据的类型
- 2,3)) x = mx.nd.zeros((
- x.dtype
- 2,3), dtype='int32') y = mx.nd.zeros((
- y.dtype
2.转换
- #转为标量,形状必须是(1,)
- 1,), dtype='int32') x = mx.nd.ones((
- x.asscalar()
- 1
- type(x.asscalar())
- #复制
- 2,3)) x = mx.nd.ones((
- y = x.copy()
- y.asnumpy()
- array([[ 1., 1., 1.],
- [ 1., 1., 1.]], dtype=float32)
3.创建
- #通过自身API创建
- 10)) a=nd.arange((
- a
- [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
- <NDArray 10 @cpu(0)>
- 2,3)) b=nd.zeros((
- b
- [[0. 0. 0.]
- [0. 0. 0.]]
- <NDArray 2x3 @cpu(0)>
- 2,3,1)) c=nd.ones((
- c
- [[[1.]
- [1.]
- [1.]]
- [[1.]
- [1.]
- [1.]]]
- <NDArray 2x3x1 @cpu(0)>
- #通过list创建
- 6,5,4,3,2,1] d=[
- e=nd.array(d)
- e
- [6. 5. 4. 3. 2. 1.]
- <NDArray 6 @cpu(0)>
4.形状
- #转置
- 0,6).reshape((2,3)) x = mx.nd.arange(
- x.asnumpy()
- array([[ 0., 1., 2.],
- [ 3., 4., 5.]], dtype=float32)
- x.T.asnumpy()
- array([[ 0., 3.],
- [ 1., 4.],
- [ 2., 5.]], dtype=float32)
- #改变形状
- 0,6).reshape(2,3) x = mx.nd.arange(
- x
- [[0. 1. 2.]
- [3. 4. 5.]]
- <NDArray 2x3 @cpu(0)>
- 3,2) y = x.reshape(
- y
- [[0. 1.]
- [2. 3.]
- [4. 5.]]
- <NDArray 3x2 @cpu(0)>
- #列多少不管,就明确是n行,列= (x.size/n)上整
- 2,-1) y = x.reshape(
- y
- [[0. 1. 2.]
- [3. 4. 5.]]
- <NDArray 2x3 @cpu(0)>
- #只要一行
- -3) y = x.reshape(
- y
- [0. 1. 2. 3. 4. 5.]
- <NDArray 6 @cpu(0)>
5.元素扩展
- #拼接,输入数组的唯独应该相同
- x = [[1,1],[2,2]]
- y = [[3,3],[4,4],[5,5]]
- z = [[6,6], [7,7],[8,8]]
- concat(x,y,z,dim=0) = [[ 1., 1.],
- [ 2., 2.],
- [ 3., 3.],
- [ 4., 4.],
- [ 5., 5.],
- [ 6., 6.],
- [ 7., 7.],
- [ 8., 8.]]
参考:
NDArray API
每日一学,争取进步03