PyTorch——Tensors

Tensors是一种特殊的数据结构,类似于数组和矩阵。在PyTorch中我们使用Tensors对模型以及模型参数的输入和输出进行编码。 Tensors类似于NumPy中的ndarrys,除了类似ndarrys之外,Tensors还可以运行加速在在GPU或其他硬件上。实际上,Tensors和NumPy的数组可以共享底层的内存,消除了复制数据的操作。Tensors也对自动分化的操作进行了优化。

import torch
import numpy as np

初始化Tensor

Tensors有很多方式进行初始化。

通过数据
data = [[1, 2],[3, 4]]
print(data)
x_data = torch.tensor(data)
print(x_data)

out:
[[1, 2], [3, 4]]
tensor([[1, 2],
        [3, 4]])
通过NumPy数组

Tensors可以通过NumPy数组创建

np_array = np.array(data)
print(np_array)
x_np = torch.from_numpy(np_array)
print(x_np)

out:
[[1 2]
 [3 4]]
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
随机或者是通过常量初始化

元组的尺寸通过tensor输出。

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensors = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensors} \n")

out:
Random Tensor: 
 tensor([[0.8378, 0.9185, 0.5126],
        [0.1094, 0.2860, 0.5684]]) 

Ones Tensor: 
 tensor([[1., 1., 1.],
        [1., 1., 1.]]) 

Zeros Tensor: 
 tensor([[0., 0., 0.],
        [0., 0., 0.]]) 

Tensor的属性

tensor的属性描述了它的形状、数据类型和它所运行在的硬件环境。

tensor = torch.rand(3, 4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

out:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

Tensors的业务操作

tensor有100多种业务操作,包括算法、线性代数、矩阵运算、抽样等,更多详细的操作可以通过https://pytorch.org/docs/stable/torch.html 同样的这些业务操作可以在GPU上运行,当然啦,需要配置环境,现在我就用cpu啦,后面的学习如果非得换成gpu,就换吧! tensor默认是创建在cpu上的,如果已配置gpu的环境,用下边的代码修改。

if torch.cuda.is_available():
    tensor = tensor.to('cuda')

接下来就进行一些tensor对列表的操作吧,如果你熟悉NumPy,那么你就会发现,贼简单!

索引和切片
tensor = torch.ones(4, 4)
print("Original:", tensor)
print("First row:", tensor[0])
print("First column:", tensor[:, 0])
print("Last colum:", tensor[..., -1])
tensor[:, 1] = 0
print(tensor)

out:
Original: tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last colum: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
合并tensors

可以通过torch.cat连接tensors,但需要注意维度,也可以用torch.stack合并tensors,不过可能有一点微妙的区别。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

out:
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
运算
#矩阵乘法运算,y1,y2,y3有相同的结果
print(tensor)
y1 = tensor @ tensor.T #@用来进行矩阵相乘,.T矩阵转置
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print(y1)
print(y2)
print(y3)

out:
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
单元素tensors

如果有一个单元素的tensor,可以通过item转换成Python的数值类型。

agg = tensor.sum()#求和
agg_item = agg.item()
print(agg, agg_item, type(agg_item))

out:
tensor(12.) 12.0 <class 'float'>
原位操作(即不允许使用临时变量)

函数表示通过 _ 后缀,例如,x.copy_(),x.t_(),改变x的值。

print(tensor,"\n")
tensor.add_(5)
print(tensor)

out:
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]]) 

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

桥接NumPy

cpu和Numpy数组上的tensors可以共享底层内存,改变其中一个同时会改变另一个。

Tensor转NumPy数组
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

out:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

修改tensor同时NumPy数组也会改变。

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

out:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
NumPy数组转Tensor
n = np.ones(5)
t = torch.from_numpy(n)
print(f"n: {n}")
print(f"t: {t}")
np.add(n, 1, out=n)
print(f"n: {n}")
print(f"t: {t}")

out:
n: [1. 1. 1. 1. 1.]
t: tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值