学习笔记|Pytorch使用教程01(张量简介与创建)

39 篇文章 24 订阅

学习笔记|Pytorch使用教程01

本学习笔记主要摘自“深度之眼”,做一个总结,方便查阅。
使用Pytorch版本为1.2。

  • Tensor的概念
  • Tensor的创建一:直接创建
  • Tensor的创建二:依据数值创建
  • Tensor的创建三:依据概率创建
  • 作业

1.Tensor的概念

1.1.张量是一个多维数组,它是标量、向量、矩阵的高维拓展。
在这里插入图片描述
1.2 Tensor与Variable
在这里插入图片描述
1.3 Tensor
在这里插入图片描述

2.Tensor的创建一:直接创建

2.1 torch.tensor()
在这里插入图片描述
功能:从data创建tensor

  • data:数据,可以是list,numpy
  • dtype:数据类型,默认与data一致
  • device:所在设备,cuda/cpu
  • requires_grad:是否需要梯度
  • pin_memory:是否存于锁页内存

测试代码

# ===============================  exmaple 1 ===============================
# 通过torch.tensor创建张量
#
flag = True
#flag = False
if flag:
    arr = np.ones((3, 3))
    print("ndarray的数据类型:", arr.dtype)

    #t = torch.tensor(arr, device='cuda')
    t = torch.tensor(arr)

    print(t)

输出:

ndarray的数据类型: float64
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)

2.2 torch.from_numpy(ndarray)

  • 功能:从numpy创建tensor
  • 注意事项:从torch.from_numpy(ndarray)创建的tensor于原ndarray共享内存,当修改其中一个数据,另外一个也将会被改动
    在这里插入图片描述
    测试代码:
# ===============================  exmaple 2 ===============================
# 通过torch.from_numpy创建张量
flag = True
#flag = False
if flag:
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    t = torch.from_numpy(arr)
    print("numpy array: ", arr)
    print("tensor : ", t)

    # print("\n修改arr")
    # arr[0, 0] = 0
    # print("numpy array: ", arr)
    # print("tensor : ", t)

    print("\n修改tensor")
    t[0, 0] = -1
    print("numpy array: ", arr)
    print("tensor : ", t)

输出:

numpy array:  [[1 2 3]
 [4 5 6]]
tensor :  tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)

修改tensor
numpy array:  [[-1  2  3]
 [ 4  5  6]]
tensor :  tensor([[-1,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)

3.Tensor的创建二:依据数值创建

3.1 torch.zeros()
在这里插入图片描述
功能:依size创建全0张量

  • size:张量的形状,如(3, 3)、(3, 224, 224)
  • out:输出的张量 (内存地址一致)
  • layout:内存中布局形式,有strided,sparse_coo等。
  • device:所在设备,gpu/cpu。
  • requires_gard:是否需要梯度。
    测试代码:
# ===============================  exmaple 3 ===============================
# 通过torch.zeros创建张量
flag = True
#flag = False
if flag:
    out_t = torch.tensor([1])
    print("out_t:",out_t)
    t = torch.zeros((3, 3), out=out_t)

    print("t:",t, '\n', "out_t:",out_t)
    print(id(t), id(out_t), id(t) == id(out_t))

输出:

out_t: tensor([1])
t: tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 out_t: tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2098704787400 2098704787400 True

3.2 torch.zeros_like()
在这里插入图片描述
功能:依input形状创建全0张量

  • input:创建与input同形状的全0张量
  • dtype:数据类型
  • layout:内存中布局形式
  • device:所在设备,gpu/cpu。
  • requires_gard:是否需要梯度。
    3.3 torch.ones()
    在这里插入图片描述
    功能:依size创建全0张量
  • size:张量的形状,如(3, 3)、(3, 224, 224)
  • out:输出的张量 (内存地址一致)
  • layout:内存中布局形式,有strided,sparse_coo等。
  • device:所在设备,gpu/cpu。
  • requires_gard:是否需要梯度。

3.4 torch.ones_like()
在这里插入图片描述
功能:依input形状创建全1张量

  • input:创建与input同形状的全0张量

  • dtype:数据类型

  • layout:内存中布局形式

  • device:所在设备,gpu/cpu。

  • requires_gard:是否需要梯度。
    3.5 torch.full()
    在这里插入图片描述
    功能:依size创建全0张量

  • size:张量的形状,如(3, 3)

  • fill_value:张量的值

3.6 torch.full_like()
功能:依input形状创建全0张量
测试代码:

# ===============================  exmaple 4 ===============================
# 通过torch.full创建全1张量
flag = True
#flag = False
if flag:
    t = torch.full((3, 3), 1)
    print(t)

输出:

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

3.7 torch.arange()
在这里插入图片描述
功能:创建等差的1维张量
注意事项:数值区间为[start, end)

  • start:数列起始值
  • end:数列“结束值”
  • step:数列公差,默认为1
    测试代码:
# ===============================  exmaple 5 ===============================
# 通过torch.arange创建等差数列张量
flag = True
#flag = False
if flag:
    t = torch.arange(2, 10, 2)
    print(t)

输出:

tensor([2, 4, 6, 8])

3.9 torch.linspace()
在这里插入图片描述
功能:创建均分的1维张量
注意事项:数值区间为[start, end)

  • start:数列起始值
  • end:数列结束值
  • steps:数列长度

测试代码:

# ===============================  exmaple 6 ===============================
# 通过torch.linspace创建均分数列张量
flag = True
#flag = False
if flag:
    # t = torch.linspace(2, 10, 5)
    t = torch.linspace(2, 10, 6)
    print(t)

输出:

tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])

3.10 torch.eye()
在这里插入图片描述
功能:创建单位对角矩阵(2维张量)
注意事项:默认为方阵

  • n:矩阵行数
  • m:矩阵列数

4.Tensor的创建三:依据概率创建

4.1 torch.normal()
在这里插入图片描述
功能:生成正太分布(高斯分布)

  • mean:均值
  • std:标准差
    四种模式:
  • mean为标量,std为标量
  • mean为标量,std为张量
  • mean为张量,std为标量
  • mean为张量,std为张量
    测试代码:
# ===============================  exmaple 7 ===============================
# 通过torch.normal创建正态分布张量
flag = True
# flag = False
if flag:
    
    # mean:张量 std: 张量
    print("1. mean:张量 std: 张量")
    mean = torch.arange(1, 5, dtype=torch.float)
    std = torch.arange(1, 5, dtype=torch.float)
    t_normal = torch.normal(mean, std)
    print("mean:{}\nstd:{}".format(mean, std))
    print(t_normal)

    # mean:标量 std: 标量
    print("2. mean:标量 std: 标量")
    t_normal = torch.normal(0., 1., size=(4,))
    print(t_normal)

    # mean:张量 std: 标量
    print("3. mean:张量 std: 标量")
    mean = torch.arange(1, 5, dtype=torch.float)
    std = 1
    t_normal = torch.normal(mean, std)
    print("mean:{}\nstd:{}".format(mean, std))
    print(t_normal)
    
    # mean:标量 std: 张量
    print("4. mean:标量 std: 张量")
    mean = 0
    std = torch.arange(1, 5, dtype=torch.float)
    t_normal = torch.normal(mean, std)
    print("mean:{}\nstd:{}".format(mean, std))
    print(t_normal)    
    

输出:

1. mean:张量 std: 张量
mean:tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([1.6614, 2.5338, 3.1850, 6.4853])
2. mean:标量 std: 标量
tensor([-0.4519, -0.1661, -1.5228,  0.3817])
3. mean:张量 std: 标量
mean:tensor([1., 2., 3., 4.])
std:1
tensor([-0.0276,  1.4369,  2.1077,  3.9417])
4. mean:标量 std: 张量
mean:0
std:tensor([1., 2., 3., 4.])
tensor([-0.1955, -1.9313,  1.2672,  1.0693])

5.作业

1.张量与矩阵、向量、标量的关系是怎么样的?

张量为一个多维数组,是标量、向量、矩阵的高维拓展。
Tensor(张量)类似于NumPy的ndarray,但还可以在GPU上使用来加速计算。

  • 标量(Scalar):0阶( r = 0 r=0 r=0)张量
  • 向量(Vector):1阶( r = 1 r=1 r=1)张量
  • 矩阵(Matrix):2阶( r = 2 r=2 r=2)张量

2.Variable“赋予”张量什么功能?

0.4.0 版本后Variable已并入Tensor
Variable是torch.autograd中的数据类型,主要用于封装Tensor,进行

  • data: 被包装的Tensor
  • grad: data的梯度
  • grad_fn: 创建Tensor的Function,是自动求导的关键
  • requires_grad:指示是否需要梯度
  • is_leaf:指示是否叶子结点

3 采用torch.from_numpy创建张量,并打印查看ndarray和张量数据的地址

torch.from_numpy(ndarray)

  • 功能:从numpy创建tensor
  • 注意事项:从torch.from_numpy创建的tensor与原ndarray共享内存,当修改其中一个数据时,另外一个也将被改动

测试代码:

3.1 创建ndarray数组

import numpy as np
import torch
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr, id(arr)
print("arr:",arr)
print("id(arr):",id(arr))

输出:

arr: [[1 2 3]
 [4 5 6]]
id(arr): 2067185197744

3.2 ndarray转tensor

import numpy as np
import torch

#3.1
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr, id(arr)
print("arr:",arr)
print("id(arr):",id(arr))
#3.2
t = torch.from_numpy(arr)
t, id(t)
print("t:",t)
print("id(t):",id(t))

输出:

arr: [[1 2 3]
 [4 5 6]]
id(arr): 2067186175472
t: tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)
id(t): 2067204134856

3.3 修改ndarray,对应tensor也发生改变

import numpy as np
import torch

#3.1
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr, id(arr)
print("arr:",arr)
print("id(arr):",id(arr))
#3.2
t = torch.from_numpy(arr)
t, id(t)
print("t:",t)
print("id(t):",id(t))
#3.3
arr[0, 0] = 99
arr, id(arr)
print("arr:",arr)
print("id(arr):",id(arr))
print("t:",t)
print("id(t):",id(t))
print("t.data:",t.data)

输出:

arr: [[1 2 3]
 [4 5 6]]
id(arr): 2067186174672
t: tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)
id(t): 2067204524456
arr: [[99  2  3]
 [ 4  5  6]]
id(arr): 2067186174672
t: tensor([[99,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)
id(t): 2067204524456
t.data: tensor([[99,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)

4 实现torch.normal()创建张量的四种模式

torch.normal()

  • 功能:生成正太分布(高斯分布)
  • mean为标量,std为标量
  • mean为标量,std为张量
  • mean为张量,std为标量
  • mean为张量,std为张量

测试一:

import torch

# mean为标量,std为标量
mean = 0
std = 1
t_normal = torch.normal(mean, std, size=(4,5))
print("mean:",mean)
print("std:",std)
print("t_normal:",t_normal)

输出:

mean: 0
std: 1
t_normal: tensor([[-1.8475, -2.9167, -0.5673, -1.1992,  0.3470],
        [-0.6537,  1.5586,  0.4001,  2.4423, -0.3818],
        [ 0.4327,  1.6499,  0.4235,  0.5730, -1.7962],
        [-0.3061, -0.4203,  0.2828,  0.3642, -0.0798]])

测试二:

import torch

# mean为标量,std为张量
mean = 1
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print("mean:",mean)
print("std:",std)
print("t_normal:",t_normal)

输出:

mean: 1
std: tensor([1., 2., 3., 4.])
t_normal: tensor([ 2.6263,  5.3546, -2.8636, -4.4254])

测试三:

import torch

# mean为张量,std为标量
mean = torch.arange(1, 5, dtype=torch.float)
std = 1
t_normal = torch.normal(mean, std)
print("mean:",mean)
print("std:",std)
print("t_normal:",t_normal)

输出:

mean: tensor([1., 2., 3., 4.])
std: 1
t_normal: tensor([-0.2245,  0.3232,  3.5173,  4.3349])

测试四:

import torch

# mean为张量,std为张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print("mean:",mean)
print("std:",std)
print("t_normal:",t_normal)

输出:

mean: tensor([1., 2., 3., 4.])
std: tensor([1., 2., 3., 4.])
t_normal: tensor([ 0.6081,  4.7547,  5.1618, -9.3220])
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值