学习笔记——pytorch1.9.0官方文档快速入门(一)

参考

官方文档——张量Tensor
运行环境:google colab

笔记链接

Tensor介绍

  张量是与数组和矩阵非常类似的数据结构。pytorch使用张量编码模型的input和output以及模型参数。Tensor与numpy的ndarray类似,区别是tensor可以运行在GPU环境中。


  导入包

import torch
import numpy as np

初始化张量的方法

数据直接转换

  tensor会自动推断出数据的类型。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
x_data

在这里插入图片描述

numpy数组转换

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

在这里插入图片描述

其他张量转换

  除非明确覆盖,否则新的张量保留参数张量的属性(形状、数据类型)。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

在这里插入图片描述

使用随机值或常量值

  举例说明:变量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}")

在这里插入图片描述

张量属性

张量属性描述了它们的形状、数据类型和存储它们的设备。

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}")

在这里插入图片描述

张量操作

  默认情况下,张量是在CPU上创建的。我们需要使用.to方法(在检查GPU可用性之后)显式地将张量移动到GPU。请记住,跨设备复制大规模的张量在时间和内存方面的开销可能很大!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

在这里插入图片描述

索引和切片

  类似于numpy。

tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)

在这里插入图片描述

拼接

  torch.cat沿着给定的维度连接一系列张量。torch.stack与前者略有不同。
  所有张量都需要相同的大小。

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

在这里插入图片描述

  tensor是2维张量,这意味着给定的维度只能是0或1(按行或按列)。若dim=1,则三个tensor按列拼接,即字面意思的[tensor,tensor,tensor]
在这里插入图片描述

算术运算

  矩阵乘法的三种形式。

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)

在这里插入图片描述

  矩阵中的元素逐一相乘。

# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

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

在这里插入图片描述

单元素张量

  若有一个单元素张量,例如通过将张量的所有值聚合为一个值,可以使用 item() 将其转换为 Python 数值:

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

在这里插入图片描述

In-place操作

  将结果存储到操作数中的操作被称为In-place。它们由 _后缀表示。例如:x.copy_(y), x.t_(),会改变x
  注意:In-place节省了一些内存,但在计算微分时可能会出现问题,因为会立刻丢失历史记录。因此,不鼓励使用它们。

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

在这里插入图片描述

tensor与numpy

  在pytorch中,tensor与numpy共享底层存储位置,改变一个就会改变另一个。

tensor转换为numpy array

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

在这里插入图片描述
  倘若改变张量,我们会发现张量的变化反映在 NumPy 数组中。

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

在这里插入图片描述

numpy array转换为tensor

n = np.ones(5)
t = torch.from_numpy(n)

  同理,改变numpy,观察tensor的变化。

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值