00_pytorch_fundamentals

123 阅读1分钟

运行环境

推荐使用google colab, colab已经提供了相应的环境,并且预先安装好了pytorch, 我们还可以选择开启GPU/TPU加速

使用 !nvidia-smi 可查看colab提供的运行环境

截屏2022-11-13 上午1.24.22.png

如上图中显示,colab本次给我们提供的是Tesla T4显卡,如果付费成为colab pro会员,会获得更好的硬件,比如Tesla p100

Tensor

tensor是深度学习中的基础数据结构

分别使用torch.tensor建立标量、向量(1维)、矩阵(2维)和 Tensor(3维及以上)

import torch

print(torch.__version__)


scalar = torch.tensor(7)
scalar # 输出: tensor(7)

scalar.shape  # torch.Size([])
scalar.ndim # 0

# Get tensor back as python int
scalar.item()
# Vector
vector = torch.tensor([3, 3])
vector  # tensor([3, 3])
vector.ndim # 1
vector.shape # torch.Size([2])




# MATRIX
MATRIX = torch.tensor([[1, 2],
                       [3, 4]])

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

MATRIX.ndim # 2
MATRIX.shape # torch.Size([2, 2])



# TENSOR

TENSOR = torch.tensor([[[1, 2, 3],
                        [3, 6, 9],
                        [2, 4, 5]]])

TENSOR # tensor([[[1, 2, 3], [3, 6, 9], [2, 4, 5]]])
TENSOR.ndim # 3
TENSOR.shape # torch.Size([1, 3, 3])

Random Tensor

深度学习中,开始时的参数一般是随机生成的,随后经过对数据的学习,不断去更新参数weights,使得loss function(损失函数)不断减小

# torch.rand [0,1) uniform distribution
random_tensor = torch.rand(3, 4)
random_tensor

# tensor([[0.9138, 0.8768, 0.7720, 0.4124], 
#         [0.0676, 0.2925, 0.0673, 0.7260], 
#         [0.8034, 0.3912, 0.7308, 0.6557]])



# Create a random tensor with similar shape to an image tensor
random_image_size_tensor = torch.rand(size=(3, 224, 224))

Zeros and ones tensor

### Zeros and ones

zeros = torch.zeros(size=(3, 4))
zeros # tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])

ones = torch.ones(size=(3, 4))

ones.dtype # torch.float32