Pytorch for former Torch users - Tensors

Pytorch for former Torch users - Tensors

Tensors

Pytorch 中的 Tensor 和 Torch 中的 Tensor 有着几乎相同的用法
创建一个 (5*7) 大小的未初始化的tensor

import torch
a = torch.empty(5, 7, dtype=torch.floar)

初始化一个从标准正态分布随机获得的双精度浮点数的tensor

b = torch.randn(5, 7, dtype=torch.double)
print(b.size())
# torch.Size([5, 7])

Note: torch.Size 实际上是一个元组(tuple)

Inplace / Out-of-place

tensor上所有就地操作都会在加有后缀 _
例如,add是易地版本, add_是就地版本

有些操作,例如narrow没有就地版本,而像fill_的操作没有易地版本

Zero Indexing

Pytorch中tensor是索引是从0开始的
a = b[0, 3] # 从b选择第1行,第4列
Tensors还可以使用Python的切片索引
b = a[:, 3:5] # 选择所有行,第4和第5列

No Camel Casing 无驼峰拼写法

所有的函数名都不再采用驼峰拼写法. 例如 indexAdd 现在改写为 index_add_

x = torch.ones(5, 5);
# tensor([[ 1.,  1.,  1.,  1.,  1.],
#         [ 1.,  1.,  1.,  1.,  1.],
#         [ 1.,  1.,  1.,  1.,  1.],
#         [ 1.,  1.,  1.,  1.,  1.],
#         [ 1.,  1.,  1.,  1.,  1.]])
z = torch.empty(5, 2)
z[:, 0] = 10
z[:, 1] = 100
# tensor([[  10.,  100.],
#         [  10.,  100.],
#         [  10.,  100.],
#         [  10.,  100.],
#         [  10.,  100.]])
x.index_add_(1, torch.tensor([4, 0]), z)
# 在x的第一维方向(水平方向), x的第五列(索引为4)加z的第一列,x的第一列(索引为0)加z的第二列
# tensor([[ 101.,    1.,    1.,    1.,   11.],
#         [ 101.,    1.,    1.,    1.,   11.],
#         [ 101.,    1.,    1.,    1.,   11.],
#         [ 101.,    1.,    1.,    1.,   11.],
#         [ 101.,    1.,    1.,    1.,   11.]])

Numpy 桥

Numpy array 和 torch Tensor之间的转换非常简单,两者之间会共享内存地址,即改变一个另一个也会随之改变.

把torch Tensor 转换成numpy Array

a = torch.ones(5)
# tensor([ 1.,  1.,  1.,  1.,  1.])
b = a.numpy()
# [1. 1. 1. 1. 1.]
a.add_(1)
# tensor([ 2.,  2.,  2.,  2.,  2.])
# [2. 2. 2. 2. 2.]

把numpy Array 转换成torch Tensor

a = np.ones(5)
b = torch.from_numpy(a)
# [1. 1. 1. 1. 1.] 
# tensor([ 1.,  1.,  1.,  1.,  1.], dtype=torch.float64)

CUDA Tensors

在Pytorch中CUDA Tensors简单好用,从CPU转换一个CUDA Tensors到GPU会保存其原始类型

# Let us run this cell only cuda is available
if torch.cuda.is_available():
    # create a LongTensor and transfer it
    # to GPU as torch.cuda.LongTensor
    a = torch.full((10, ), 2, device=torch.device("cuda"))
    print(a)
    b = a.to(torch.device("cpu"))
    # transfer it to CPU, back to
    # being a torch.LongTensor
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值