PyTorch教程2:Tensor创建

278 阅读6分钟

公众号:尤而小屋
编辑:Peter
作者:Peter

大家好,我是Peter~

本文介绍如何在PyTorch中创建Tensor,这是使用PyTorch进行深度学习的第一步,也是最为基础的一步。最后介绍PyTorch中常用的数据类型,以及如何进行设置和改变。

导入库

import pandas as pd
import numpy as np

import torch
from torch import nn 
from torch.utils.data import DataLoader,Dataset  # utils是工具包
from torchvision import datasets
from torchvision.transforms import ToTensor

首先介绍基于多个函数或方法来创建不同的Tensor:

使用torch.tensor()

1、从Python列表创建Tensor:

lst = [1,2,3,4]

tensor1 = torch.tensor(lst)
tensor1 

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

type(tensor1)  # 查看数据类型 

torch.Tensor

2、从numpy数组创建Tensor:

numpy_arr = np.array([1,2,3,4])

tensor2 = torch.tensor(numpy_arr) 
tensor2

tensor([1, 2, 3, 4], dtype=torch.int32)

使用torch.from_numpy()

通过torch.from_numpy函数来生成也极其方便:

tensor3 = torch.from_numpy(numpy_arr)  # 使用numpy数组
tensor3

tensor([1, 2, 3, 4], dtype=torch.int32)

使用torch_rand()、torch_randn()、torch.randint()或torch.rand_like()

四者用于创建随机初始化的Tensor:

  • torch.rand():生成均匀分布的随机数
  • torch.randn():生成符合标准正态分布的随机数
  • torch.randint():生成指定区间上的随机数
  • torch.rand_like():基于某个张量的shape进行创建
tensor4 = torch.rand(3,2)  # 均匀分布:0-1之间
tensor4
tensor([[0.0321, 0.8543],
        [0.9155, 0.5947],
        [0.9626, 0.5966]])
tensor5 = torch.randn(4,2)  # 标准正态分布
tensor5 
tensor([[-1.9809,  0.0465],
      [-0.8754, -0.1601],
      [ 0.0491,  0.4267],
      [ 1.8975, -0.1706]])
tensor6 = torch.randint(1,10,[3,3])  # 在1-10的区间内生成3*3的张量数组
tensor6 
    tensor([[2, 3, 1],
            [8, 8, 8],
            [7, 8, 4]])


tensor7 = torch.rand_like(tensor5)  # 基于tensor5的shape进行创建
tensor7
tensor([[0.5240, 0.0075],
      [0.8406, 0.0995],
      [0.0233, 0.9488],
      [0.3570, 0.5491]])

使用torch.empty或torch.empty_like()

二者都是用来创建空数组:

tensor8 = torch.empty((4,2), dtype=torch.float32)
tensor8 
tensor([[6.3058e-44, 6.8664e-44],
      [7.0065e-44, 6.3058e-44],
      [6.8664e-44, 6.7262e-44],
      [1.1771e-43, 6.7262e-44]])

创建和指定Tensor的shape相同的空Tensor:

tensor9 = torch.empty_like(tensor5)
tensor9
tensor([[6.8664e-44, 6.7262e-44],
      [1.1771e-43, 6.7262e-44],
      [7.7071e-44, 8.1275e-44],
      [7.4269e-44, 7.0065e-44]])

使用torch.FloatTensor或torch.IntTensor

二者用于生成随机的浮点数或者整数的张量:

tensor10 = torch.FloatTensor(2, 3)  # 浮点数
tensor10
tensor([[6.3058e-44, 6.8664e-44, 7.0065e-44],
      [6.3058e-44, 6.8664e-44, 6.7262e-44]])

tensor11 = torch.IntTensor(2, 3)  # 整数
tensor11

tensor([[ 862139493,  761409637, 1684104801],
    [1684157485,  828452193,  925721654]], dtype=torch.int32)

使用torch.full()

表示使用相同的元素进行创建:

tensor12 = torch.full([3,2],8)  # 相同元素为8  shape为3*2
tensor12
tensor([[8, 8],
      [8, 8],
      [8, 8]])

使用torch.normal()

torch.normal 是 PyTorch 中用于生成正态分布(高斯分布)随机数的函数。它允许用户指定生成随机数的形状、均值和标准差等参数。

torch.normal(mean, std, generator=None, out=None)
  • mean (Tensor or float): 正态分布的均值。可以是一个标量或一个与输出形状相同的张量。
  • std (Tensor or float): 正态分布的标准差。可以是一个标量或一个与输出形状相同的张量。
  • generator (torch.Generator, optional): 用于生成随机数的随机数生成器。如果未指定,则使用全局默认生成器。
  • out (Tensor, optional): 可选的输出张量。如果提供,结果将存储在该张量中
# 生成一个形状为 (3, 3) 的正态分布随机数矩阵,均值为0,标准差为1

tensor13 = torch.normal(0, 1, size=(3, 3)) 
tensor13
tensor([[-2.1242, -0.3209, -0.5634],
      [ 0.1115, -1.2329, -1.4103],
      [-1.4714,  0.3987,  0.0533]])
tensor14 = torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))
tensor14
tensor([0.8983, 1.8828, 2.7534, 4.6313, 5.4092, 
6.8502, 7.7716, 7.9289, 8.6098,9.9055])
tensor15 = torch.normal(mean=torch.arange(1., 6.))
tensor15
tensor([1.0791, 2.9477, 2.9525, 3.6380, 6.6513])

使用torch.zeros()或torch.zeros_like()

二者都用于创建全0的Tensor:

tensor16 = torch.zeros([4,3]) 
tensor16
tensor([[0., 0., 0.],
      [0., 0., 0.],
      [0., 0., 0.],
      [0., 0., 0.]])
tensor17 = torch.zeros_like(tensor5)  # 基于tensor5的shape创建全0张量
tensor17
tensor([[0., 0.],
      [0., 0.],
      [0., 0.],
      [0., 0.]])

使用torch.ones()或torch.ones_like()

二者都用于创建全1的Tensor:

tensor18 = torch.ones([4,3]) 
tensor18
tensor([[1., 1., 1.],
      [1., 1., 1.],
      [1., 1., 1.],
      [1., 1., 1.]])
tensor19 = torch.ones_like(tensor7)  # 基于tensor7的shape 
tensor19
tensor([[1., 1.],
      [1., 1.],
      [1., 1.],
      [1., 1.]])

使用torch.arange()

用于创建等间隔的Tensor:指定步长

tensor20 = torch.arange(1,20)  # 不包含尾部;间隔默认为1
tensor20
tensor([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 
11, 12, 13, 14, 15, 16, 17, 18,19])
tensor21 = torch.arange(1,20,3)  # 改变间隔
tensor21
tensor([ 1,  4,  7, 10, 13, 16, 19])

使用torch.linespace()

用于创建等间隔的Tensor:指定个数

tensor22 = torch.linspace(1,20,steps=50)  # 包含尾部;在1到20直接等间隔取50个数
tensor22 
tensor([ 1.0000,  1.3878,  1.7755,  2.1633,  2.5510,  2.9388,  3.3265,  3.7143,
       4.1020,  4.4898,  4.8776,  5.2653,  5.6531,  6.0408,  6.4286,  6.8163,
       7.2041,  7.5918,  7.9796,  8.3673,  8.7551,  9.1429,  9.5306,  9.9184,
      10.3061, 10.6939, 11.0816, 11.4694, 11.8571, 12.2449, 12.6327, 13.0204,
      13.4082, 13.7959, 14.1837, 14.5714, 14.9592, 15.3469, 15.7347, 16.1224,
      16.5102, 16.8980, 17.2857, 17.6735, 18.0612, 18.4490, 18.8367, 19.2245,
      19.6122, 20.0000])

使用torch.eye()

用于创建单位矩阵tensor

tensor23 = torch.eye(3)  # 必须是二维
tensor23
tensor([[1., 0., 0.],
      [0., 1., 0.],
      [0., 0., 1.]])
tensor24 = torch.eye(5,4)  # 必须是二维
tensor24
tensor([[1., 0., 0., 0.],
      [0., 1., 0., 0.],
      [0., 0., 1., 0.],
      [0., 0., 0., 1.],
      [0., 0., 0., 0.]])

使用torch.diag()

用于创建对角矩阵:

tensor25 = torch.diag(torch.tensor([1, 2, 3]))
tensor25
tensor([[1, 0, 0],
      [0, 2, 0],
      [0, 0, 3]])

使用torch.diagonal

用于提取对角线元素:

tensor26 = torch.diagonal(tensor25)
tensor26 

tensor([1, 2, 3])

使用torch.tril()或torch.triu()

  • torch.tril():创建下三角矩阵
  • torch.triu():创建上三角矩阵
tensor18 
tensor([[1., 1., 1.],
      [1., 1., 1.],
      [1., 1., 1.],
      [1., 1., 1.]])
tensor27 = torch.tril(tensor18)  # 下三角
tensor27
tensor([[1., 0., 0.],
      [1., 1., 0.],
      [1., 1., 1.],
      [1., 1., 1.]])
tensor28 = torch.triu(tensor18)  # 上三角
tensor28
tensor([[1., 1., 1.],
    [0., 1., 1.],
    [0., 0., 1.],
    [0., 0., 0.]])

PyTorch数据类型

最后介绍以下PyTorch中常见的数据类型:

常见类型

浮点数类型

  • torch.float32 (或 torch.float): 32位浮点数,单精度。
  • torch.float64 (或 torch.double): 64位浮点数,双精度。
  • torch.float16 (或 torch.half): 16位浮点数,半精度。
  • torch.bfloat16: 16位浮点数,BFLOAT16,一种介于 float16 和 float32 之间的格式。

整数类型

  • torch.int8: 8位有符号整数。
  • torch.uint8: 8位无符号整数。
  • torch.int16: 16位有符号整数。
  • torch.short: 16位有符号整数,与 torch.int16 相同。
  • torch.int32 (或 torch.int): 32位有符号整数。
  • torch.int64 (或 torch.long): 64位有符号整数。

布尔类型

  • torch.bool: 布尔类型,表示 True 或 False。

复数类型

  • torch.complex64: 由两个 32位浮点数组成的复数。
  • torch.complex128: 由两个 64位浮点数组成的复数。

其他类型

  • torch.qint8: 量化的 8位整数,通常用于量化神经网络中的权重。
  • torch.quint8: 量化的 8位无符号整数。
  • torch.qint32: 量化的 32位整数。

设置数据类型

使用torch.tensor传入浮点数元素,或者使用torch.Tensor仅指定维度时,生成的默认是FloatTensor,也可以设置为其它类型的:

torch.set_default_tensor_type(torch.DoubleTensor)

改变数据类型

tensor29 = torch.tensor([1,2,3])  
tensor29

tensor([1, 2, 3])

tensor29.dtype  # 默认为int64

torch.int64

tensor30 = torch.tensor([1,2,3], dtype=torch.int32)  # 指定为int32
tensor30

tensor([1, 2, 3], dtype=torch.int32)

tensor30.dtype 

torch.int32

改变数据类型方式1:

tensor31 = tensor30.long()
tensor31

tensor([1, 2, 3])

tensor31.dtype  # 从int32---->int64

torch.int64

改变数据类型方式2:

tensor32 = tensor30.type(torch.int64)
tensor32

tensor([1, 2, 3])

tensor32.dtype  # 从int32---->int64

torch.int64

参考

1、官网:pytorch.org/tutorials/b…

2、PyTorch中文教程:pytorch.ac.cn/tutorials/b…

3、动手学深度学习:zh.d2l.ai/index.html