第二章 预备知识

2.2 数据操作

2.2.1 创建NDArray(Mxnet)、Tensor(Pytorch)

Mxnet Pytorch
from mxnet import nd import torch
创建向量 nd.zeros((4,2)), nd.ones((4,2)) torch.zeros(4, 2), torch.zeros(4, 2)
创建向量 x = nd.arange(12) x = torch.arange(12)
获取形状 x.shape x.shape
获取元素总数 x.size x.size
更改形状 x.reshape(3, 4) x.reshape((3, 4))
从list创建 nd.array([5.5, 3]) torch.tensor([5.5, 3])
随机生成 nd.random.normal(0, 1, shape=(3, 4)) torch.randn(3, 4)

注:
1、pytorch输入形状参数可用单小括号或双小括号,例如 torch.zeros(4, 2),等同torch.zeros((4, 2)),Mxnet必须为双小括号

2.2.2 运算

Mxnet Pytorch
四则运算 x+y x+y
指数运算 x.exp() x.exp()
矩阵乘法 nd.dot(x, y.T) torch.mm(x, y.T)
合并 nd.concat(x, y, dim=0) torch.cat((x, y), dim=0)
判断 x == y (返回 True 或 Falue) x == y (返回 1 或 0)

2.2.6 和NumPy相互变换

Mxnet Pytorch
由np转入 nd.array(x) torch.from_numpy(x)
转出到np x.asnumpy() x.numpy()

2.3 自动求梯度

Mxnet Pytorch
创建变量 x = nd.arange(4).reshape((4, 1)) x = torch.ones(4, 1, requires_grad=True)
申请存储梯度所需要的内存 x.attach_grad() 上一步已申请
with autograd.record():
y = 2 * nd.dot(x.T, x)
y = 2 * torch.mm(x.T, x)
自动求梯度 y.backward() y.backward()
读取梯度 x.grad x.grad
发布了9 篇原创文章 · 获赞 0 · 访问量 197

猜你喜欢

转载自blog.csdn.net/qinhuiqiao/article/details/104312903