1.Tensor

文章详细介绍了PyTorch中的Tensor数据结构,包括如何从数据、numpy数组和其他Tensor初始化,以及Tensor的属性如形状、数据类型和设备。此外,还讨论了Tensor的索引、切片、连接、算术运算等操作,并提到了GPU上的计算。
摘要由CSDN通过智能技术生成

1. Tensor

Tensor是在PyTorch中的一种特殊数据结构,类似于数组和矩阵。在PyTorch中,使用Tensor对模型的输入和输出以及模型的参数进行编码。

1.1 初始化一个Tensor

1.1.1 根据数据

Tensor可以直接从数据中创建,并自动判断数据类型。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
print(f"x_data:{x_data}")

tensor([[1, 2],
[3, 4]])

1.1.2 根据numpy数组

Tensor可以和numpy数组相互转换

# numpy转为tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(f"x_np:{x_np}")
# tensor转为numpy
tensor2np = x_np.numpy()
print(f"tensor2np:{tensor2np}")

x_np:tensor([[1, 2],
[3, 4]], dtype=torch.int32)
tensor2np:[[1 2]
[3 4]]

1.1.3 根据其他Tensor

新tensor保留作为参数的tensor的属性(形状、数据类型),除非对其属性进行重写

x_ones = torch.ones_like(x_data) # 保留x_data的属性
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写x_data的数据类型
print(f"Random Tensor: \n {x_rand} \n")

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

Random Tensor:
tensor([[0.7354, 0.6289],
[0.9268, 0.4886]])

1.1.4 根据随机数或常数

shape是tensor的维度元组,它决定了输出张量的维数。

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = 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_tensor}")

Random Tensor:
tensor([[0.0535, 0.2257, 0.9594],
[0.8522, 0.3476, 0.2888]])

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

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

1.2 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}")
# 若GPU可用,将其移动到GPU上
if torch.cuda.is_available():
    tensor = tensor.to("cuda")
print(f"Device tensor is stored on: {tensor.device}")

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

1.3 Tensor的操作

这里全面描述了100多种Tensor运算,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等。这些操作中的每一个都可以在GPU上运行(通常比在CPU上运行的速度更高)。默认情况下,tensor是在CPU上创建的。可以使用.to方法(GPU可用时)将tensor移动到GPU。

1.3.1 标准的类似numpy的索引和切片
tensor = torch.ones(2, 3)
print(f"第一行: {tensor[0]}")
print(f"第一列: {tensor[:, 0]}")
print(f"最后一列: {tensor[..., -1]}")
# 将第1列的数据替换为0
tensor[:,1] = 0
print(tensor)

第一行: tensor([1., 1., 1.])
第一列: tensor([1., 1.])
最后一列: tensor([1., 1.])
tensor([[1., 0., 1.],
[1., 0., 1.]])

1.3.2 连接tensor

可以使用torch.cattorch.stack沿给定维度连接tensor。

torch.cat(在已有维度连接tensor)
# 行连接
t0 = torch.cat([tensor, tensor, tensor], dim=0)
print(t0)
# 列连接
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

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

torch.stack(在新的维度连接tensor)
t0 = torch.stack([tensor, tensor, tensor], dim=0)
print(t0)
t1 = torch.stack([tensor, tensor, tensor], dim=1)
print(t1)
t2 = torch.stack([tensor, tensor, tensor], dim=2)
print(t2)

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

1.3.3 算术运算
矩阵乘积
# tensor.T 表示 tensor的转置
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
# 创建变量y3,用于接收乘积的值
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)

y1:tensor([[2., 2.],
[2., 2.]]),
y2:tensor([[2., 2.],
[2., 2.]]),
y3:tensor([[2., 2.],
[2., 2.]])

Hadamard积(对应元素乘积)
# 矩阵对应元素乘积
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

z1:tensor([[1., 0., 1.],
[1., 0., 1.]]),
z2:tensor([[1., 0., 1.],
[1., 0., 1.]]),
z3:tensor([[1., 0., 1.],
[1., 0., 1.]])

1.3.4 单元素tensor

若tensor中仅有一个元素,则可以使用item(),将其转为python数值。

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

tensor(4.) <class ‘torch.Tensor’>
4.0 <class ‘float’>

1.3.5 就地操作

将结果直接存储到操作数中。它们用后缀_表示。例如:x.copy_(y)x.t_()将更改x的值。

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

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

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

参考资料

  1. https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
  2. https://www.bbsmax.com/A/MyJx4nD1Jn/
  3. https://blog.csdn.net/Blankit1/article/details/131262108
  4. https://blog.csdn.net/wzk4869/article/details/127932435
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值