pytorch升级打怪(二)

张量

简介

张量是一种专门的数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量来编码模型的输入和输出,以及模型的参数。

张量与NumPy的ndarrays相似,只是张量可以在GPU或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享相同的底层内存,无需复制数据(请参阅带有NumPy的桥接)。张量也针对自动分化进行了优化(我们稍后将在Autograd部分看到更多信息)。如果您熟悉ndarrays,您就可以在家使用Tensor API。如果没有,请跟随!

初始化张量

python 复制代码
import torch
import numpy as np

#直接来自数据
#张量可以直接从数据中创建。数据类型被自动推断。

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

#从NumPy数组
#张量可以从NumPy数组创建(反之亦然-请参阅带有NumPy的桥接)。

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

#来自另一个张量:
#新张量保留参数张量的属性(形状、数据类型),除非明确覆盖。

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是张量维度的元组。在下面的函数中,它决定了输出张量的维度。

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

张量的属性

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

python 复制代码
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}")
shell 复制代码
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

张量的操作

这里全面描述了100多个张量运算,包括算术、线性代数、矩阵操作(转位、索引、切片)、采样等。

这些操作中的每一个都可以在GPU上运行(通常速度比CPU快)。如果您使用的是Colab,请转到运行时>更改运行时类型>GPU来分配GPU。

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

python 复制代码
# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

标准numpy样索引和切片

python 复制代码
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
shell 复制代码
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

算术运算

python 复制代码
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
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)
shell 复制代码
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

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

python 复制代码
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
shell 复制代码
12.0 <class 'float'>

将结果存储到操作数中的就地操作称为就地操作。它们用一个_后缀表示。例如:x.copy_(y)x.t_()将更改x。

python 复制代码
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
shell 复制代码
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阵列上的张量可以共享其底层内存位置,更改一个将改变另一个

张量到NumPy数组

python 复制代码
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
shell 复制代码
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

张量的变化反映在NumPy数组中。

python 复制代码
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
shell 复制代码
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

NumPy阵列到张量

python 复制代码
n = np.ones(5)
t = torch.from_numpy(n)

NumPy数组的变化反映在张量中。

python 复制代码
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
shell 复制代码
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
相关推荐
AcaDesign26 分钟前
国家/省部市级科技奖答辩PPT_科技进步奖_自然科学奖_技术发明奖|WordinPPT
大数据·人工智能·科技·powerpoint
Ai-_Man2 小时前
希望大家能推荐一款软件,可以直接把文心生成的代码变流程图,提高办公效率
人工智能·ai·小程序·流程图
AI02265 小时前
探秘AI Agent软件公司:开启智能时代的创新引擎
人工智能
fīɡЙtīиɡ ℡7 小时前
AI 应用系统设计
java·开发语言·人工智能
小淮AI7 小时前
国际教育课程的本土化探索:以枫叶教育三十年为观察样本
大数据·人工智能
又折桃枝换酒钱7 小时前
VisCoder2:构建多语言可视化编码智能体(翻译与解读)
人工智能·信息可视化
AI绘画哇哒哒7 小时前
【建议收藏!】35岁后端血泪忠告,这3类人别硬转Agent(过来人亲述)
java·人工智能·后端·ai·程序员·大模型·agent
Chengbei117 小时前
DSH渗透测试插件dsh-pentest全新升级!适配DeepSeek Harness,可视化探索链路,一键搭建轻量化AI渗透测试环境。
人工智能·web安全·网络安全·微信·小程序·系统安全·安全架构
QN1幻化引擎7 小时前
DalinX Phi 性能突破:跨层秩保持对齐与意识涌现度量的实证研究
人工智能·ai·架构·agi·asi