【PyTorch攻略(1/7)】 张量基本语法

一、说明

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

张量类似于 NumPyndarray, 除了张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存地址,具有称为桥接到 np 标签 的功能,这消除了复制数据的需要。张量也针对自动微分进行了优化。如果你熟悉ndarrays,那么你就可以熟悉Tensor API。如果没有,请跟着走!
让我们从设置环境开始。

ajz 复制代码
%matplotlib inline
import torch
import numpy as np

二、初始化张量

张量可以通过多种方式初始化。例如:

  • 直接从数据
ajz 复制代码
data = [[1,2], [3,4]]
x_data = torch.tensor(data)
  • 从数字派数组

张量可以从 NumPy 数组创建,反之亦然。由于 numpy 'np_array ' 和张量 'x_np' 共享相同的内存位置,因此更改其中一个的值将影响另一个。

ajz 复制代码
np_array = np.array
x_np = torch.from_numpy(np_array)
  • 从另一个张量
ajz 复制代码
x_ones = torch.ones_like(x_data)
x_rand = torch.rand_like(x_data, dtype = torch.float)
  • 使用随机值或常量值

在下面的函数中,它确定输出张量的维数。形状 是张量维度的元组。它显示了张量中的行数和列数,例如,shape =(#行,#列)。

ajz 复制代码
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}")
ack 复制代码
Random Tensor: 
 tensor([[0.4424, 0.4927, 0.5646],
        [0.7742, 0.0868, 0.3927]]) 

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

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

2.1 张量的属性

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

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

T这里有 100 多种张量运算,包括算术、线性代数、矩阵操作(转置、索引、切片)。这些操作中的每一个都可以在 GPU 上运行。

  • CPU 最多有 16 个内核。核心是执行实际计算的单元。每个核心按顺序处理任务(一次一个任务)。
  • GPU 有 1000 个内核。GPU 内核以并行处理方式处理计算。任务在不同的内核之间划分和处理。这就是在大多数情况下使GPU比CPU更快的原因。GPU 处理大数据的性能优于处理小数据。GPU 通常用于图形或神经网络的高强度计算。

默认情况下,张量是在 CPU 上创建的。张量也可以计算到 GPU;为此,您需要使用 .to 方法移动它们(在检查 GPU 可用性之后)。

ajz 复制代码
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

2.2 索引和切片张量

ajz 复制代码
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)
ack 复制代码
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.]])

2.3 连接张量

ajz 复制代码
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
ack 复制代码
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.]])

您可以使用 torch.cat 沿给定维度连接一系列张量。torch.stack 是另一个与 torch.cat 略有不同的张量连接选项。

2.4 算术运算

ajz 复制代码
# This computes the matrix multiplication between two tensors. 
# y1, y2, y3 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 have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
ack 复制代码
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

2.5 单元素张量

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

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

2.6 就地操作

ajz 复制代码
print(tensor, "\n")
tensor.add_(5)
print(tensor)
ack 复制代码
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.]])

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

2.7 张量到 NumPy 数组

ajz 复制代码
t = torch.ones(5)
n = t.numpy()
print(f"t: {t}")
print(f"n: {n}")

# A change in tensor reflects in the NumPy array.
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
ack 复制代码
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

2.8 NumPy 数组到张量

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

# A change in Numpy array reflects in the tensor.
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
ack 复制代码
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

下一>> PyTorch 简介 (2/7)

相关推荐
奈斯。zs16 分钟前
yjs08——矩阵、数组的运算
人工智能·python·线性代数·矩阵·numpy
Melody205016 分钟前
tensorflow-dataset 内网下载 指定目录
人工智能·python·tensorflow
学步_技术17 分钟前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
DisonTangor1 小时前
阿里通义千问开源Qwen2.5系列模型:Qwen2-VL-72B媲美GPT-4
人工智能·计算机视觉
豆浩宇1 小时前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
Narutolxy1 小时前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
LLSU131 小时前
聚星文社AI软件小说推文软件
人工智能
JackieZhengChina1 小时前
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
人工智能·智能手机
ShuQiHere1 小时前
【ShuQiHere】 探索数据挖掘的世界:从概念到应用
人工智能·数据挖掘
嵌入式杂谈1 小时前
OpenCV计算机视觉:探索图片处理的多种操作
人工智能·opencv·计算机视觉