PyTorch Handbook 2.1.1基础 张量

import torch
import numpy

torch.__version__
'1.12.1'

张量(Tensor)

张量的英文是Tensor,它是PyTorch里面基础的运算单位,与Numpy的ndarray相同都表示的是一个多维的矩阵。
与ndarray的最大区别就是,PyTorch的Tensor可以在 GPU 上运行,而 numpy 的 ndarray 只能在 CPU 上运行,在GPU上运行大大加快了运算速度。

x = torch.rand(2, 3)
x
tensor([[0.6615, 0.3260, 0.1040],
        [0.8035, 0.9080, 0.3676]])
# 可以使用与numpy相同的shape属性查看
print(x.shape)
# 也可以使用size()函数,返回的结果都是相同的
print(x.size())
torch.Size([2, 3])
torch.Size([2, 3])

张量(Tensor)是一个定义在一些向量空间和一些对偶空间的笛卡儿积上的多重线性映射,其坐标是|n|维空间内,有|n|个分量的一种量, 其中每个分量都是坐标的函数, 而在坐标变换时,这些分量也依照某些规则作线性变换。r称为该张量的秩或阶(与矩阵的秩和阶均无关系)

y = torch.rand(2, 3,4,5)
y.size()
torch.Size([2, 3, 4, 5])
y
tensor([[[[0.5266, 0.0868, 0.7097, 0.9420, 0.9697],
          [0.7293, 0.8190, 0.6888, 0.3311, 0.2345],
          [0.5521, 0.8252, 0.0654, 0.2144, 0.4513],
          [0.1506, 0.3645, 0.4237, 0.2272, 0.9405]],

         [[0.4590, 0.5817, 0.9888, 0.4842, 0.6701],
          [0.1944, 0.7189, 0.1076, 0.1867, 0.1993],
          [0.0864, 0.8774, 0.0549, 0.5186, 0.0807],
          [0.1684, 0.1752, 0.0510, 0.5342, 0.6797]],

         [[0.7640, 0.1326, 0.0051, 0.7388, 0.0070],
          [0.9256, 0.2997, 0.6976, 0.6932, 0.2339],
          [0.1241, 0.5640, 0.0976, 0.5607, 0.8151],
          [0.0192, 0.3523, 0.9312, 0.7479, 0.8681]]],


        [[[0.5069, 0.0748, 0.5342, 0.4175, 0.6440],
          [0.4008, 0.2009, 0.5512, 0.0223, 0.8227],
          [0.3345, 0.1473, 0.3857, 0.9773, 0.6777],
          [0.3819, 0.6051, 0.1134, 0.5279, 0.9662]],

         [[0.7911, 0.5542, 0.8608, 0.9358, 0.6979],
          [0.5827, 0.4737, 0.4609, 0.3673, 0.2389],
          [0.6973, 0.9327, 0.7258, 0.1549, 0.6795],
          [0.1100, 0.9302, 0.7436, 0.8288, 0.6289]],

         [[0.0304, 0.4450, 0.0227, 0.5300, 0.9539],
          [0.1997, 0.0773, 0.4542, 0.3670, 0.2770],
          [0.6596, 0.3267, 0.5612, 0.3899, 0.7470],
          [0.8292, 0.2948, 0.3789, 0.8167, 0.1223]]]])

在同构的意义下,第零阶张量 (r = 0) 为标量 (Scalar),第一阶张量 (r = 1) 为向量 (Vector), 第二阶张量 (r = 2) 则成为矩阵 (Matrix),第三阶以上的统称为多维张量。

# 直接使用现有数字生成
scalar = torch.tensor(3.1433244)
print(scalar)
scalar.size()
tensor(3.1433)





torch.Size([])
#对于标量,我们可以直接使用 .item() 从中取出其对应的python对象的数值
scalar.item()
3.143324375152588

特别的:如果张量中只有一个元素的tensor也可以调用tensor.item方法

tensor = torch.tensor([3.14444])
print(tensor)
tensor.size()
tensor([3.1444])





torch.Size([1])
tensor.item()
3.144439935684204

基本类型

Tensor的基本数据类型有五种:

32位浮点型:torch.FloatTensor。 (默认)

64位整型:torch.LongTensor。

32位整型:torch.IntTensor。

16位整型:torch.ShortTensor。

64位浮点型:torch.DoubleTensor。

除以上数字类型外,还有
byte和chart型

long = tensor.long()
print(long)
print(long.dtype)
tensor([3])
torch.int64
half = tensor.half()
half
tensor([3.1445], dtype=torch.float16)
int_t = tensor.int()
int_t
tensor([3], dtype=torch.int32)
flo = tensor.float()
print(flo)
print(flo.dtype)
tensor([3.1444])
torch.float32
short = tensor.short()
short
tensor([3], dtype=torch.int16)
ch = tensor.char()
ch
tensor([3], dtype=torch.int8)
bt = tensor.byte()
bt
tensor([3], dtype=torch.uint8)

Numpy转换

使用numpy方法将Tensor转为ndarray

a = torch.randn((3,2))
# tensor转化为numpy
numpy_a = a.numpy()
print(numpy_a)
[[ 0.3827394   0.29910496]
 [-1.7304703   1.0511789 ]
 [-0.03787737  1.620995  ]]

numpy转化为Tensor

torch_a = torch.from_numpy(numpy_a)
torch_a
tensor([[ 0.3827,  0.2991],
        [-1.7305,  1.0512],
        [-0.0379,  1.6210]])

Tensor和numpy对象共享内存,所以他们之间的转换很快,而且几乎不会消耗什么资源。但这也意味着,如果其中一个变了,另外一个也会随之改变。

设备间转换

一般情况下可以使用.cuda方法将tensor移动到gpu,这步操作需要cuda设备支持

cpu_a=torch.rand(4, 3)
cpu_a.type()
'torch.FloatTensor'
gpu_a=cpu_a.cuda()
gpu_a.type()
'torch.cuda.FloatTensor'

使用.cpu方法将tensor移动到cpu

cpu_b= gpu_a.cpu()
cpu_b.type()
'torch.FloatTensor'

如果我们有多GPU的情况,可以使用to方法来确定使用那个设备,这里只做个简单的实例:

#使用torch.cuda.is_available()来确定是否有cuda设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

# 将tensor传送到设备
gpu_b = cpu_b.to(device)
gpu_b.type()
cuda





'torch.cuda.FloatTensor'

初始化

Pytorch中有许多默认的初始化方法可以使用

# 使用[0,1]均匀分布随机初始化二维数组
rnd = torch.rand(5, 3)
rnd
tensor([[0.2024, 0.0185, 0.0283],
        [0.1944, 0.5437, 0.5443],
        [0.6346, 0.4509, 0.8133],
        [0.5719, 0.1039, 0.8547],
        [0.5110, 0.4665, 0.2393]])
##初始化,使用0填充
zero=torch.zeros(2,2)
zero
tensor([[0., 0.],
        [0., 0.]])
#初始化一个单位矩阵,即对角线为1 其他为0
eye=torch.eye(2,2)
eye
tensor([[1., 0.],
        [0., 1.]])
##初始化,使用1填充
one = torch.ones(2, 2)
one
tensor([[1., 1.],
        [1., 1.]])

常用方法

PyTorch中对张量的操作api 和 NumPy 非常相似,如果熟悉 NumPy 中的操作,那么他们二者基本是一致的:

x = torch.randn(3, 3)
print(x)
tensor([[-0.1212,  0.0240, -1.5718],
        [-1.2435, -1.0624,  0.0478],
        [ 1.1807,  0.4033,  1.8967]])
# 沿着行取最大值
max_value, max_idx = torch.max(x, dim=1)
print(max_value, max_idx)
tensor([0.0240, 0.0478, 1.8967]) tensor([1, 2, 2])
# 每行 x 求和
sum_x = torch.sum(x, dim=1)
print(sum_x)
tensor([-1.6690, -2.2581,  3.4807])
y=torch.randn(3, 3)
z = x + y
print(z)
tensor([[ 1.1031,  0.5894, -1.5726],
        [-2.5141, -0.3041, -1.5271],
        [ 1.4237,  2.1406,  2.3018]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值