pytorch基础1-pytorch介绍与张量操作

专题链接:https://blog.csdn.net/qq_33345365/category_12591348.html

本教程翻译自微软教程:https://learn.microsoft.com/en-us/training/paths/pytorch-fundamentals/

初次编辑:2024/3/1;最后编辑:2024/3/1


这是本教程的第一篇,分为:

  1. 介绍pytorch基础
  2. 张量操作

另外本人还有pytorch CV相关的教程,见专题:

https://blog.csdn.net/qq_33345365/category_12578430.html


介绍

大多数机器学习工作流程都涉及处理数据、创建模型、使用超参数优化模型、保存和推断已训练的模型。本模块介绍在 PyTorch 中实现的完整机器学习(ML)工作流程,PyTorch 是一种流行的 Python ML 框架。

本教程使用 FashionMNIST 数据集来训练一个神经网络模型,该模型可以识别图像,如 T 恤/上衣、裤子、套衫、连衣裙、外套、凉鞋、衬衫、运动鞋、包包或短靴。

在构建模型之前,会展示构建神经网络模型的关键概念。

学习目标:

  1. 学习如何在 CPU 和 GPU 上使用张量(Tensors)
  2. 理解如何管理、扩展和规范化数据集
  3. 使用神经网络构建图像识别模型
  4. 学习如何优化模型
  5. 学习如何提高模型推理性能

先修要求:

基本的 Python 知识


什么是张量 Tensor

张量

张量是一种专门的数据结构,非常类似于数组和矩阵。PyTorch使用张量来编码模型的输入和输出,以及模型的参数。张量类似于NumPy数组和ndarrays,但是张量可以在GPU或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享相同的底层内存地址,具有称为bridge-to-np-label的功能,这消除了复制数据的需要。张量还针对自动微分进行了优化。

设置基本环境:

import torch
import numpy as np

初始化一个张量

张量可通过多种方式初始化,见如下例子:

1. 直接通过数据初始化

张量可以直接从数据中创建。数据类型是自动推断的。

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

2. 从一个NumPy数组

张量可以从NumPy数组创建,反之亦然。由于numpy格式的np_array和张量格式x_np在这里共享相同的内存位置,改变其中一个的值将会改变另一个的值。

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

print(f"Numpy np_array value: \n {np_array} \n")
print(f"Tensor x_np value: \n {x_np} \n")

np.multiply(np_array, 2, out=np_array)

print(f"Numpy np_array after * 2 operation: \n {np_array} \n")
print(f"Tensor x_np value after modifying numpy array: \n {x_np} \n")

输出是:

Numpy np_array value: 
 [[1 2]
 [3 4]] 

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

Numpy np_array after * 2 operation: 
 [[2 4]
 [6 8]] 

Tensor x_np value after modifying numpy array: 
 tensor([[2, 4],
        [6, 8]], dtype=torch.int32) 

3. 从其他张量

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

输出是:

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

Random Tensor: 
 tensor([[0.7907, 0.9041],
        [0.4805, 0.0954]]) 

4. 使用随机数或常量

shape由张量维度的元组定义,它设置了张量的行数和列数。在下面的函数中,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}")

输出:

Random Tensor: 
 tensor([[0.5893, 0.4485, 0.6525],
        [0.9083, 0.2913, 0.0752]]) 

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

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

张量的属性 Attributes of a 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}")

输出是:

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

有100多个张量操作,包括算术运算、线性代数、矩阵操作(如转置、索引和切片)。可以在找到全面的描述。

这些操作中的每一个都可以在GPU上运行(通常比在CPU上速度更快)。

  • CPU的核心数少于100个。核心是执行实际计算的单元。每个核心按顺序处理任务(一次处理一个任务)。

  • GPU有数千乃至上万个核心。GPU核心以并行处理的方式处理计算,任务被分割并在不同核心上处理。这就是为什么在大多数情况下GPU比CPU更快的原因。GPU在处理大数据时表现比小数据更好,因为更有利于并行加速。GPU通常用于图形或神经网络的高强度计算。

  • PyTorch可以使用Nvidia CUDA库来利用其GPU卡。

GPU并不总是优于CPU,因为CPU的单核性能强,因此在处理小数据时可能更占优势。

默认情况下,张量在CPU上创建。张量也可以移动到GPU;为此,需要使用.to方法将它们移动(在检查GPU可用性后)。当然,由于CPU和GPU之间的传输跨设备,这意味着传输上的巨大开销。

# 如果GPU可用则将tensor移动到GPU上,GPU可用需要保证1. CUDA安装;2. 安装对应CUDA版本的pytorch,见https://pytorch.org/,选择合适的pytorch安装方式
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

类似numpy的标准索引和切片 Standard numpy-like indexing and slicing

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)

输出是:

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.]])

拼接张量

可以使用 torch.cat 函数沿着指定维度连接一个张量序列。torch.stack是一个相关的张量拼接方法,它沿着新的维度将一个张量序列堆叠起来。以下例子,维度有四个可选值:

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

dim=1;输出:

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.]])

dim=0,输出:

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.]])

dim=-1,输出:

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.]])

dim=-2,输出:

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的值是一样的
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

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


# 它计算元素级乘积,Z1 z2 z3的值是一样的
z1 = tensor * tensor
z2 = tensor.mul(tensor)

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

print(y3)
print(z3)

输出:

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

单元素张量

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

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

输出:

12.0 <class 'float'>

原地操作 in-place operations

将结果存储到操作数(operand)中的操作称为原地操作。它们通常用下划线_作为后缀。例如:x.copy_(y),x.t_(),会改变x的值。

注意: 就地操作可以节省一些内存,但在计算导数时可能会出现问题,因为它们会立即丢失历史记录。因此,不建议使用它们。

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

输出:

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桥接 Bridge with Numpy

NumPy数组和CPU上的张量可以共享它们的底层内存位置,改变其中一个将改变另一个。

张量到NumPy数组的转换

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

输出:

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.]

NumPy数组到张量的转换

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

输出:

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

代码汇总

import torch
import numpy as np

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

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

print(f"Numpy np_array value: \n {np_array} \n")
print(f"Tensor x_np value: \n {x_np} \n")

np.multiply(np_array, 2, out=np_array)

print(f"Numpy np_array after * 2 operation: \n {np_array} \n")
print(f"Tensor x_np value after modifying numpy array: \n {x_np} \n")

# 从其他张量
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")

# random and constant
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}")

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

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

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)

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

# 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)

print(y3)
print(z3)

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

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

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

n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
  • 40
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

whyte王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值