ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

【深度学习】Day1

【深度学习】Day1

张量的创建


张量

  • 张量(Tensor):
    PyTorch 张量是一种用于存储多维数组的数据结构,类似于 NumPy 的多维数组,是深度学习里最基础的数据载体

  • 张量按维度分为下面几类:

张量基本创建方式

  • torch.tensor()
    根据给定数据创建张量,小写tensor
    1)传入列表 / 数组,自动推断数据类型
    # 用列表创建张量 t1=torch.tensor([1,2,3]) print(t1) # tensor([1, 2, 3])
    2)特点:拷贝数据,新建张量;
    日常开发首选
  • torch.Tensor()
    大写Tensor,有两种用法:

    1)传入数字形状:创建指定 shape 的张量(内容未初始化,随机垃圾值)
    t2=torch.Tensor(2,3) # 创建2行3列张量 print(t2)

    2)传入列表数据:也可以创建张量(不推荐,容易混淆)
    t3=torch.Tensor([1,2,3]) print(t3)

    3)注意:大写torch.Tensor默认是float32类型;
    小写torch.tensor会根据输入自动判断类型
  • torch.IntTensor / torch.FloatTensor / torch.DoubleTensor
    1)创建指定数据类型的张量
    (旧 API 写法,新版本更推荐在torch.tensor里用dtype=指定类型)
    2)
    # 整型张量 t_int=torch.IntTensor([1,2,3]) # 浮点型张量 float32 t_float=torch.FloatTensor([1.1,2.2]) # 双精度浮点 float64 t_double=torch.DoubleTensor([1.1,2.2]) print(t_int) print(t_float) print(t_double)


    更推荐写法:
    t = torch.tensor([1, 2, 3], dtype=torch.int32) print(t)
  • 重点区分
torch.tensor ()
  • torch.tensor():
    根据传入的数据创建张量,可以传入数字、numpy 数组、Python 列表,会自动继承输入的数据类型

  • # 1 创建张量标量(0维张量) data=torch.tensor(10) print(data) data1=np.random.randn(2,3) # numpy 默认 float64 data2=torch.tensor(data1) print(data2) # 3. python 创建列表 data3=[[1,2,3],[4,5,6]] data4=torch.tensor(data3) print(data4)

  • 关键点
    1)torch.tensor(10):传入单个数字,生成0 维标量张量,
    输出tensor(10),不是数组形式
    2)numpy 数组转张量
    a)numpy 的浮点数默认是float64,所以生成的张量dtype=torch.float64b)torch.tensor()会拷贝一份数据,新张量和原 numpy 数组互不影响
    3)Python 列表创建张量
    a)列表里写带小数点数字10.,代表浮点数,PyTorch 默认转成float32b)两层列表[[...],[...]]→2 维张量(矩阵)

torch.Tensor ()
  • 两种写法
    1)传数字(形状参数):创建指定形状的张量,不初始化,
    里面是内存里残留的随机垃圾值
    2)传列表:创建带指定数据的张量
    默认数据类型:float32

  • # 1. 创建2行3列的张量,只指定形状,里面的值没初始化的随机值 data=torch.Tensor(2,3) print(data) # 2. 传入列表,按照列表数据创建张量 data1=torch.Tensor([10,20,30]) print(data1) data2=torch.Tensor([10]) print(data2)

  • 核心对比

torch.IntTensor/ FloatTensor / DoubleTensor

  • 传数字((2,3)):创建指定形状、对应数据类型的未初始化张量(内存残留垃圾值)

  • 传列表数据:自动把里面元素强制转换成对应类型
  • # 1. 创建2行3列,dtype=int32 的张量,没初始化,里面的是随机脏整数 data=torch.IntTensor(2,3) print(data) # 2. 传入浮点列表,自动强制转成int32,小数直接砍掉,不是四舍五入,是截断 data1=torch.IntTensor([2.5,3.3]) print(data1) # 3. 其他旧版类型 data2=torch.ShortTensor() # int 16 data3=torch.LongTensor() # int 64 data4=torch.FloatTensor() # int 32 data5=torch.DoubleTensor() # int 64

  • 新版推荐写法
    1)torch.tensor() + 指定 dtype 参数,可读性更好
    data=torch.tensor([2.5,3.3],dtype=torch.int32) print(data)


创建线性 随机张量


线性张量
  • torch.arange(start, end, step)
    (1)区间:[start, end),左闭右开;按步长生成

    data=torch.arange(0,10,2) print(data) # tensor([0, 2, 4, 6, 8])
  • torch.linspace(start, end, steps)
    (1)区间:[start, end],首尾都包含;按元素总个数均分
    data = torch.linspace(0,9,10) print(data) # tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

随机张量相关
  • torch.manual_seed(seed_num)
    (1)设置随机种子,固定种子后,后续随机数每次运行结果完全一样,用于实验复现
    (2)torch.initial_seed():查看当前随机种子

  • torch.randn(*size)
    (1)生成标准正态分布(均值 0,方差 1)的浮点张量
    torch.manual_seed(100) data=torch.randn(2,3) # 2 行3 列 print(data) # tensor([[ 0.3607, -0.2859, -0.3938], # [ 0.2429, -1.3833, -2.3134]])
  • torch.randint(low, high, size=())
    (1)生成随机整数张量,区间[low, high)
    data=torch.randint(0,10,size=(2,3)) # 2 行3列 print(data) # tensor([[2, 0, 4], # [2, 3, 8]])


使用torch.arange() 和 torch.linspace()创建线性张量

  • def demo1(): # 1.使用torch.arange()创建一个从0到9的线性张量 [0,10) t1=torch.arange(0,10) print(f"t1:{t1},shape:{t1.shape}, dtype: {t1.dtype}") # 2.使用torch.linspace()创建一个从0到9的线性张量,一共10个点 t2= torch.linspace(0,9,10) print(f"t2: {t2}, shape:{t2.shape}, dtype:{t2.dtype}")


    torch.Size() 就是专门用来描述张量形状的类型,和列表很像
    (1)torch.Size([10])→ 1 维,长度 10
    (2)torch.Size([3,5])→ 2 维,3 行 5 列(3 个行,每行 5 个元素)
    (3)torch.Size([2,3,4])→ 3 维

  • 创建随机张量

    def demo02(): # 0.设置随机种子 # torch.random.manual_seed(28) torch.manual_seed(28) # 1.使用torch.rand创建一个随机张量,shape(3,5),[0,1)均匀分布 t1 = torch.rand(3,5) print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}") # 2.使用torch.randn创建一个随机张量,(3,5),标准正态分布 t2 = torch.randn(3,5) print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}") # 3.使用torch.randint创建一个随机整数张量,(3,5),区间[0,10) t3 = torch.randint(0,10,(3,5)) print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}") # 4.打印当前随机种子 print(f"当前随机种子:{torch.initial_seed()}")




  • 总结
    (1)torch.arange(0,10):整数序列,左闭右开,默认 int64
    (2)torch.linspace(0,9,10):均分,首尾都包含,默认 float32
    (3)torch.rand(3,5):0~1 均匀分布,只有正数
    (4)torch.randn(3,5):标准正态分布,有正有负
    (5)torch.randint(0,10,(3,5)):整数,[low, high)
    (6)torch.manual_seed(28):固定随机种子,保证每次运行随机数不变



全 0 / 全 1 / 指定值张量


  • 后缀带 _like 的函数:参考另一个张量的 shape、dtype、设备,来新建张量

  • torch.zeros() / torch.zeros_like() —— 全 0 张量
    # zeros(shape):直接指定形状 data=torch.zeros(2,3) print(data) # tensor([[0., 0., 0.], # [0., 0., 0.]]) # zeros_like(已有张量):复用data的shape data1=torch.zeros_like(data) print(data1) # tensor([[0., 0., 0.], # [0., 0., 0.]])
  • torch.ones()/torch.ones_like()—— 全 1 张量
    # ones(shape) data=torch.ones(2,3) print(data) # tensor([[1., 1., 1.], # [1., 1., 1.]]) # ones_like data1=torch.ones_like(data) print(data1) # tensor([[1., 1., 1.], # [1., 1., 1.]])
  • torch.full()/torch.full_like()—— 填充指定数值
    # full(shape, fill_value) 注意shape要写成列表 [2,3] data=torch.full([2,3],10) print(data) # tensor([[10, 10, 10], # [10, 10, 10]]) data1=torch.full_like(data,20) print(data1) # tensor([[20, 20, 20], # [20, 20, 20]])


代码

  • torch.zeros 和 torch.zeros_like 创建全0张量
  • torch.ones 和 torch.ones_like 创建全1张量
  • torch.full 和 torch.full_like 创建全为指定值张量
  • 用处: 网络参数初始化,偏置参数初始化

  1. 创建全0张量
    def demo01(): # 1.使用torch.zeros创建全0张量,(3,4) t1 = torch.zeros(3,4) print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}") # 2.创建一个随机张量,(3,5) t2 = torch.randn(3,5) print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}") # 3.使用torch.zeros_like创建相同形状的全0张量 t3 = torch.zeros_like(t2) # (3,5) print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")



  2. 创建全1张量
    def demo02(): # 1.使用torch.ones创建全1张量,(3,4) t1 = torch.ones(3,4) print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}") # 2.创建一个随机张量,(3,5) t2 = torch.randn(3,5) print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}") # 3.使用torch.ones_like创建相同形状的全1张量 t3 = torch.ones_like(t2) # (3,5) print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")



  3. 创建指定值张量
    def demo03(): # 1.使用torch.full创建指定值张量,(3,4) t1 = torch.full((3,4),10) print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}") # 2.创建一个随机张量,(3,5) t2 = torch.randn(3,5) print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}") # 3.使用torch.full_like创建相同形状的指定值张量 t3 = torch.full_like(t2,10) # (3,5) print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}")



RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进