## 动手学深度学习-数据操作

``````#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/4/9 14:11
# @Author  : cunyu
# @Site    : cunyu1943.github.io
# @File    : dataOperation.py
# @Software: PyCharm

from mxnet import nd

"""

"""

# 创建行向量
rowX = nd.arange(12)
print(rowX)

# 获取NDArray实例形状
shapeOfRowX = rowX.shape
print(shapeOfRowX)

# 获取NDArray实例元素总数
numOfElement = rowX.size
print(numOfElement)

# 改变行向量形状
newRowX = rowX.reshape((3,4))
print(newRowX)

# 创建元素全为0的张量
tensor0 = nd.zeros((2, 3, 4))
print(tensor0)

# 创建元素均为1的张量
tensor1 = nd.ones((3, 4))
print(tensor1)

# 通过list指定要创建的NDArray中每个元素的值
tensorY = nd.array([[1,3, 4, 9], [6, 3, 4, 5], [0, 8, 9, 7]])
print(tensorY)

# 随机生成NDArray中每个每个元素的值
tensorZ = nd.random.normal(0, 1, shape = (3,4))
print(tensorZ)

"""

"""

# 加法
print(newRowX + tensorY)

# 乘除法
print(newRowX * tensorY)
print(newRowX / tensorY)

# 指数
print(tensorY.exp())
# print(nd.exp(tensorY))

# 矩阵乘法
print(nd.dot(newRowX, tensorY.T))

# 连结
print(nd.concat(newRowX, tensorY, dim=0), nd.concat(newRowX, tensorY, dim=1))

# 使用条件判别式得到元素为0/1的新的NDArray
print(newRowX == tensorY)

# 求和得到只有一个元素的NDArray
print(tensorY.sum())
# print(nd.sum(tensorY))

# 张量变换为Python中的标量
print(newRowX.norm().asscalar())
# print(nd.norm(newRowX).asscalar())

"""

"""
A = nd.arange(3).reshape((3,1))
B = nd.arange(2).reshape((1,2))
print('A + B', A + B)

""""

"""

# 截取范围
print(newRowX[1:3])

# 访问单个元素
print(newRowX[2,3])
newRowX[2, 3] = 15
print(newRowX[2,3])
print(newRowX)
newRowX[1:2, :] = 10
print(newRowX)

"""

"""

# 制造了临时内存开销
before = id(tensorY)
tensorY = newRowX + tensorY
print(id(tensorY) == before)

Z = tensorY.zeros_like()
before = id(Z)
Z[:] = newRowX + tensorY
print(id(Z) == before)

# 避免临时内存开销
print(id(Z) == before)

"""
NDArray和NumPy相互变换
"""

import numpy as np

# NumPy转NDArray
P = np.ones((2, 3))
D = nd.array(P)
print(D)

# NDArray转NumPy
print(D.asnumpy())
``````