PyTorch学习之基本操作

基本概念

Tensors:

Tensors和Numpy’s的ndarrys相似,可以在GPU上使用Tensors来加速计算。

构建矩阵(不初始化):
x = torch.Tensor(5, 3)
print(x)

构建矩阵(随机初始化):
x = torch.rand(5, 3)
Get its size
print(x.size())

加法操作(addition):
第一种方式:print(x + y)
第二种方式:print(torch.add(x, y))
第三种方式:
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
第四种方式(adds x to y):y.add_(x)

切片操作,跟numpy基本一样:
print(x[1,:])

resize/reshape:
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)

numpy和tensor转换:(共享内存,所以转换后进行操作二个会同时更新)
tensor–>numpy
a = torch.ones(5)
b = a.numpy()
a.add_(1)
print(a)
print(b)

numpy–>tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)

更多操作:http://pytorch.org/docs/master/torch.html

Autograd: automatic differentiation

Autograd 包为Tensors上的所有操作提供自动微分。

Variable
Autograd.Variable是包的核心类。它包装一个张量,支持几乎所有在其上定义的操作。 一旦你完成你的计算,你可以调用.backward()并自动计算所有的梯度。您可以通过.data属性访问原始张量,.grad得到梯度。

创建:
x = Variable(torch.ones(2, 2), requires_grad=True)
print(x)

Gradients
梯度,通过.backward()使用。

参考:
1.http://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值