PyTorch框架学习 — Tensor(张量)详解

1 Tensor 的概念

  Tensor 中文翻译为张量。张量的意思是一个多维数组,它是标量、向量、矩阵的高维扩展。标量可以称为 0 维张量,向量可以称为 1 维张量,矩阵可以称为 2 维张量,RGB 图像可以用 3 维张量表示。因此,我们可以把张量看作多维数组。

在这里插入图片描述

  在深度学习中,我们需要处理大量的数据,包括对数据的各种运算以及存储等。在PyTorch中,torch.Tensor是存储和变换数据的主要工具。如果大家了解Python的NumPy库的话,你会发现Tensor和NumPy的多维数组非常类似。然而,在PyTorch深度学习框架中,Tensor提供GPU计算和自动求梯度等更多功能,这些使Tensor更加适合深度学习。

2 Tensor 与 Variable

  在 PyTorch 0.4.0 之前,torch.autograd 包中存在 Variable 这种数据类型,主要是用于封装 Tensor,进行自动求导。Variable 主要包含下面几种属性。

  

bullet

data: 被包装的 Tensor。
  

bullet

grad: data 的梯度。
  

bullet

grad_fn: 创建 Tensor 所使用的 Function,是自动求导的关键,因为根据所记录的函数才能计算出导数。
  

bullet

requires_grad: 指示是否需要梯度,并不是所有的张量都需要计算梯度。
  

bullet

is_leaf: 指示是否为叶子节点(张量),叶子节点的概念在计算图中会用到,后面详细介绍。

在这里插入图片描述

  在 PyTorch 0.4.0 之后,Variable 并入了 Tensor。在之后版本的 Tensor 中,除了具有上面 Variable 的 5 个属性,还有另外 3 个属性。

  

bullet

dtype: 张量的数据类型,如 torch.FloatTensortorch.cuda.FloatTensor
  

bullet

shape: 张量的形状。如 (64, 3, 224, 224)
  

bullet

device: 张量所在设备 (CPU/GPU),GPU 是加速计算的关键

在这里插入图片描述

  Torch定义了10种CPU tensor类型和10种GPU tensor类型:

在这里插入图片描述

3 创建Tensor的方法

3.1 直接创建Tensor

torch.tensor()
torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor

  

bullet

data: 数据,可以是 list,NumPy ndarray,tuple,scalar 以及其他类型。
  

bullet

dtype: 返回张量的数据类型,默认与 data 的一致。
  

bullet

device: 所在设备,cuda/cpu。
  

bullet

requires_grad: 是否需要梯度。
  

bullet

pin_memory: 如果设置,返回的张量将分配到固定内存中。仅适用于CPU张量。

【代码】

import torch
torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])

【结果】

tensor([[0.1000, 1.2000],
        [2.2000, 3.1000],
        [4.9000, 5.2000]])

【代码】

import torch
torch.tensor([0, 1])  # Type inference on data

【结果】

tensor([0, 1])

【代码】

# creates a torch.cuda.DoubleTensor
t = torch.tensor([[0.11111, 0.222222, 0.3333333]], dtype=torch.float64, device=torch.device('cuda:0'))
print(t)

【结果】

tensor([[0.1111, 0.2222, 0.3333]], device='cuda:0', dtype=torch.float64)

【代码】

# Create a scalar (zero-dimensional tensor)
t = torch.tensor(3.14159)
print(t)

【结果】

tensor(3.1416)

【代码】

# Create an empty tensor (of size (0,))
t = torch.tensor([])
print(t)

【结果】

tensor([])

【代码】

import torch
import numpy as np

arr = np.ones((3, 3))
print("arr的数据类型:", arr.dtype)

# 创建存放在 GPU 的数据
t = torch.tensor(arr, device='cuda')
# t = torch.tensor(arr)
print(t)

【结果】

arr的数据类型: float64
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], device='cuda:0', dtype=torch.float64)

torch.from_numpy(ndarray)
torch.from_numpy(ndarray) → Tensor

【功能】:从 numpy 创建 tensor。利用这个方法创建的 tensor 和原来的 ndarray 共享内存,当修改其中一个数据,另外一个也会被改动。

在这里插入图片描述
【代码】

import torch
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)

# 修改 array,tensor 也会被修改
print("修改arr: ")
arr[0, 0] = 0
print("numpy array: ", arr)
print("tensor: ", t)

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

【结果】

修改arr: 
numpy array:  [[0 2 3]
 [4 5 6]]
tensor:  tensor([[0, 2, 3],
        [4, 5, 6]])

修改tensor: 
numpy array:  [[-1  2  3]
 [ 4  5  6]]
tensor:  tensor([[-1,  2,  3],
        [ 4,  5,  6]])

3.2 根据数值创建 Tensor

torch.zeros()
torch.zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:根据 size 创建全 0 张量

  

bullet

size: 定义输出张量形状的整数序列。可以是数量可变的参数或集合,如列表或元组。
  

bullet

out: 输出的张量,如果指定了 out,那么torch.zeros()返回的张量和 out 指向的是同一个地址。
  

bullet

dtype: 返回张量的数据类型。
  

bullet

layout: 内存中布局形式,有 strided,sparse_coo 等。当是稀疏矩阵时,设置为 sparse_coo 可以减少内存占用。
  

bullet

device: 所在设备,cuda/cpu。
  

bullet

requires_grad: 是否需要梯度。

【代码】

import torch

out_t = torch.tensor([1])   # 这里制定了out
t = torch.zeros((3, 3), out=out_t)
print("t = ", t)
print("out_t = ", out_t)
print("t的内存地址: ", id(t))
print("out_t的内存地址: ", id(out_t))
print(id(t) == id(out_t))

【结果】

t =  tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
out_t =  tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
t的内存地址:  140530588876928
out_t的内存地址:  140530588876928
True

torch.zeros_like()
torch.zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

【功能】:根据 input 形状创建全 0 张量

  

bullet

input: input的大小决定了输出张量的大小。
  

bullet

dtype: 返回张量的数据类型。
  

bullet

layout: 内存中布局形式,有 strided,sparse_coo 等。当是稀疏矩阵时,设置为 sparse_coo 可以减少内存占用。
  

bullet

device: 所在设备,cuda/cpu。
  

bullet

requires_grad: 是否需要梯度。
  

bullet

memory_format: 返回张量的所需内存格式。

【代码】

import torch

input = torch.empty(2, 3)
t = torch.zeros_like(input)
print("t = ", t)

【结果】

t =  tensor([[0., 0., 0.],
        [0., 0., 0.]])

  同理还有全 1 张量的创建方法:torch.ones()torch.ones_like()


torch.full()
torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:创建自定义数值的张量

  

bullet

size: 张量的形状,可以是list或tuple,如 (3,3)或[3,3]。
  

bullet

fill_value: 张量中每一个元素的值。

【代码】

import torch

t = torch.full((3, 3), 2)
print("t = ", t)

【结果】

t =  tensor([[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]])

  同理还有根据 input 形状创建自定义数值的张量:torch.full_like()


torch.arange()
torch.arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:创建等差的 1 维张量。注意区间为[start, end)。

  

bullet

start: 数列起始值,默认从0开始。
  

bullet

end: 数列结束值,开区间,取不到结束值。
  

bullet

step: 数列公差,默认为 1。

【代码】

import torch

t1 = torch.arange(5)
print("t1 = ", t1)
t2 = torch.arange(1, 4)
print("t2 = ", t2)
t3 = torch.arange(1, 2.5, 0.5)
print("t3 = ", t3)

【结果】

t1 =  tensor([0, 1, 2, 3, 4])
t2 =  tensor([1, 2, 3])
t3 =  tensor([1.0000, 1.5000, 2.0000])

torch.linspace()
torch.linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:创建均分的 1 维张量。数值区间为 [start, end]

  

bullet

start(float): 数列起始值,注意不能缺省。
  

bullet

end(float): 数列结束值,闭区间,取得到结束值。
  

bullet

step(int): 数列长度 (元素个数)。

【代码】

import torch

t1 = torch.linspace(3, 10, steps=5)
print("t1 = ", t1)
t2 = torch.linspace(-10, 10, steps=5)
print("t2 = ", t2)
t3 = torch.linspace(start=-10, end=10, steps=5)
print("t3 = ", t3)
t4 = torch.linspace(start=-10, end=10, steps=1)
print("t4 = ", t4)

【结果】

t1 =  tensor([ 3.0000,  4.7500,  6.5000,  8.2500, 10.0000])
t2 =  tensor([-10.,  -5.,   0.,   5.,  10.])
t3 =  tensor([-10.,  -5.,   0.,   5.,  10.])
t4 =  tensor([-10.])

torch.logspace()
torch.logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:创建对数均分的 1 维张量。数值区间为 [start, end],底为 base。

  

bullet

start(float): 数列起始值。
  

bullet

end(float): 数列结束值。
  

bullet

steps(int): 数列长度 (元素个数)。
  

bullet

base(float, optional): 对数函数的底,默认为 10。

【代码】

import torch

t1 = torch.logspace(-10, 10, steps=5)
print("t1 = ", t1)
t2 = torch.logspace(0.1, 1, steps=5)
print("t2 = ", t2)
t3 = torch.logspace(0.1, 1, steps=1)
print("t3 = ", t3)
t4 = torch.logspace(2, 2, steps=1, base=2)
print("t4 = ", t4)

【结果】

t1 =  tensor([1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10])
t2 =  tensor([ 1.2589,  2.1135,  3.5481,  5.9566, 10.0000])
t3 =  tensor([1.2589])
t4 =  tensor([4.])

torch.eye()
torch.eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

【功能】:创建单位对角矩阵( 2 维张量),默认为方阵

  

bullet

n(int): 矩阵行数。通常只设置 n,为方阵。
  

bullet

m(int): 矩阵列数。

【代码】

import torch

t1 = torch.eye(3)
print("t1 = ", t1)
t2 = torch.eye(2, 3)
print("t2 = ", t2)
t3 = torch.eye(3, 2)
print("t3 = ", t3)

【结果】

t1 =  tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
t2 =  tensor([[1., 0., 0.],
        [0., 1., 0.]])
t3 =  tensor([[1., 0.],
        [0., 1.],
        [0., 0.]])

3.3 根据概率创建 Tensor

torch.normal()

【功能】:返回从独立的正态分布中提取的随机数张量,其平均值和标准偏差均已给出。

  

bullet

mean: 均值
  

bullet

std: 标准差

  有 4 种模式:

  1. mean 为标量,std 为标量,这时需要设置 size。

torch.normal(mean, std, size, *, out=None) → Tensor

【代码】

import torch

t1 = torch.normal(2, 3, size=(1, 4))    
print("t1 = ", t1)

【结果】

t1 =  tensor([[3.9841, 2.8008, 2.1850, 3.8640]])
  1. mean 为标量,std 为张量,所有元素共享mean。

torch.normal(mean=0.0, std, *, out=None) → Tensor

【代码】

import torch

mean = 0.5
std = torch.arange(1, 6, dtype=torch.float)
t2 = torch.normal(mean, std)
print("mean:{}nstd:{}".format(mean, std))
print("t2 = ", t2)

【结果】

mean:0.5
std:tensor([1., 2., 3., 4., 5.])
t2 =  tensor([ 0.0481,  0.1677, -4.0683,  2.0267, -4.6380])

  这 5 个数采样分布的方差不同,但是均值都是 0.5。

  1. mean 为张量,std 为标量,所有元素共享std。

torch.normal(mean, std=1.0, *, out=None) → Tensor

【代码】

import torch

mean = torch.arange(1, 6, dtype=torch.float)
std = 1
t3 = torch.normal(mean, std)
print("mean:{}nstd:{}".format(mean, std))
print("t3 = ", t3)

【结果】

mean:tensor([1., 2., 3., 4., 5.])
std:1
t3 =  tensor([0.4369, 1.1077, 2.9417, 3.8045, 4.0344])

  这 5 个数采样分布的均值不同,但是方差都是 1。

  1. mean 为张量,std 为张量。

torch.normal(mean, std, *, generator=None, out=None) → Tensor

【代码】

import torch

mean = torch.arange(1, 6, dtype=torch.float)
std = torch.arange(1, 6, dtype=torch.float)
t4 = torch.normal(mean, std)
print("mean:{}nstd:{}".format(mean, std))
print("t4 = ", t4)

【结果】

mean:tensor([1., 2., 3., 4., 5.])
std:tensor([1., 2., 3., 4., 5.])
t4 =  tensor([ 1.4224,  2.5346,  1.7364,  1.9572, -2.8633])

  其中 1.4224 是从正态分布

N

(

1

,

1

)

N(1,1)

N(1,1) 中采样得到的,其他数字以此类推。


torch.randn()torch.randn_like()
torch.randn(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
 
torch.randn_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

【功能】:返回一个由均值为0、方差为1的正态分布(也称为标准正态分布)中的随机数填充的张量,

N

(

0

,

1

)

N(0,1)

N(0,1)

  

bullet

size(int): 定义输出张量形状的整数序列,可以是数量可变的参数或集合,如列表或元组。
  

bullet

input(Tensor): input的大小将决定输出张量的大小。

【代码】

import torch
import numpy as np

t1 = torch.randn(4)
print("t1 = ", t1)
t2 = torch.randn(2, 3)
print("t2 = ", t2)

input = torch.tensor(np.ones((3, 3)))
t3 = torch.randn_like(input)
print("t3 = ", t3)

【结果】

t1 =  tensor([0.6614, 0.2669, 0.0617, 0.6213])
t2 =  tensor([[-0.4519, -0.1661, -1.5228],
        [ 0.3817, -1.0276, -0.5631]])
t3 =  tensor([[-0.8923, -0.0583, -0.1955],
        [-0.9656,  0.4224,  0.2673],
        [-0.4212, -0.5107, -1.5727]], dtype=torch.float64)

torch.rand()torch.rand_like()
torch.rand(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
 
torch.randn_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

【功能】:返回一个由区间[0,1)上均匀分布的随机数填充的张量

  

bullet

size(int): 定义输出张量形状的整数序列,可以是数量可变的参数或集合,如列表或元组。
  

bullet

input(Tensor): input的大小将决定输出张量的大小。

【代码】

import torch
import numpy as np

t1 = torch.rand(4)
print("t1 = ", t1)
t2 = torch.rand(2, 3)
print("t2 = ", t2)

input = torch.tensor(np.ones((3, 3)))
t3 = torch.rand_like(input)
print("t3 = ", t3)

【结果】

t1 =  tensor([0.7576, 0.2793, 0.4031, 0.7347])
t2 =  tensor([[0.0293, 0.7999, 0.3971],
        [0.7544, 0.5695, 0.4388]])
t3 =  tensor([[0.1094, 0.4609, 0.7084],
        [0.5798, 0.4967, 0.5104],
        [0.3295, 0.7182, 0.3845]], dtype=torch.float64)

torch.randint()torch.randint_like()
torch.randint(low=0, high, size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
 
torch.randint_like(input, low=0, high, *, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

【功能】:返回由在[low,high)之间均匀生成的随机整数填充的张量。

  

bullet

low(int, optional): 要从分布中提取的最小整数。默认值:0。
  

bullet

high(int): 要从分布中提取的最大整数。
  

bullet

size(tuple): 定义输出张量形状的元组。
  

bullet

input(Tensor): input的大小将决定输出张量的大小。

【代码】

import torch
import numpy as np

t1 = torch.randint(3, 5, (3, ))
print("t1 = ", t1)
t2 = torch.randint(10, (2, 2))
print("t2 = ", t2)

input = torch.tensor(np.ones((3, 3)))
t3 = torch.randint_like(input, 1, 10)
print("t3 = ", t3)

【结果】

t1 =  tensor([4, 4, 3])
t2 =  tensor([[8, 3],
        [3, 1]])
t3 =  tensor([[6., 9., 1.],
        [3., 4., 2.],
        [9., 5., 1.]], dtype=torch.float64)

torch.randperm()
torch.randperm(n, *, generator=None, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

【功能】:返回从0到n-1的整数的随机排列。常用于生成索引。

  

bullet

n(int): 张量的长度

【代码】

import torch

t1 = torch.randperm(4)
print("t1 = ", t1)
t2 = torch.randperm(10)
print("t2 = ", t2)

【结果】

t1 =  tensor([1, 3, 2, 0])
t2 =  tensor([8, 0, 3, 2, 9, 4, 6, 5, 7, 1])

torch.bernoulli()
torch.bernoulli(input, *, generator=None, out=None) → Tensor

【功能】:以 input 为概率,生成伯努利分布 (0-1 分布,两点分布)。

  

bullet

input(Tensor): 一个包含用于获取二进制随机数的概率的张量,input中的每个值都必须在[0,1]之间。

【代码】

import torch

a = torch.empty(3, 3).uniform_(0, 1)
print("a = ", a)
t1 = torch.bernoulli(a)
print("t1 = ", t1)

a = torch.ones(3, 3)
print("a = ", a)
t2 = torch.bernoulli(a)
print("t2 = ", t2)

【结果】

a =  tensor([[0.7576, 0.2793, 0.4031],
        [0.7347, 0.0293, 0.7999],
        [0.3971, 0.7544, 0.5695]])
t1 =  tensor([[1., 0., 0.],
        [1., 0., 1.],
        [0., 1., 1.]])
a =  tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
t2 =  tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

4 完整代码

import torch
import numpy as np
torch.manual_seed(1)


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

    # 创建存放在 GPU 的数据
    t = torch.tensor(arr, device='cuda')
    # t = torch.tensor(arr)
    print(t)


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

    # 修改 array,tensor 也会被修改
    print("修改arr: ")
    arr[0, 0] = 0
    print("numpy array: ", arr)
    print("tensor: ", t)

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


# ===============================  exmaple 3 ===============================
# 通过torch.zeros创建张量
# flag = True
flag = False
if flag:
    out_t = torch.tensor([1])   # 这里制定了out
    t = torch.zeros((3, 3), out=out_t)
    print("t = ", t)
    print("out_t = ", out_t)
    print("t的内存地址: ", id(t))
    print("out_t的内存地址: ", id(out_t))
    print(id(t) == id(out_t))


# ===============================  exmaple 4 ===============================
# 通过torch.zeros_like创建张量
# flag = True
flag = False
if flag:
    input = torch.empty(2, 3)
    t = torch.zeros_like(input)
    print("t = ", t)


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


# ===============================  exmaple 6 ===============================
# 通过torch.arange创建等差数列张量
# flag = True
flag = False
if flag:
    t1 = torch.arange(5)
    print("t1 = ", t1)
    t2 = torch.arange(1, 4)
    print("t2 = ", t2)
    t3 = torch.arange(1, 2.5, 0.5)
    print("t3 = ", t3)


# ===============================  exmaple 7 ===============================
# 通过torch.linspace创建均分数列张量
# flag = True
flag = False
if flag:
    t1 = torch.linspace(3, 10, steps=5)
    print("t1 = ", t1)
    t2 = torch.linspace(-10, 10, steps=5)
    print("t2 = ", t2)
    t3 = torch.linspace(start=-10, end=10, steps=5)
    print("t3 = ", t3)
    t4 = torch.linspace(start=-10, end=10, steps=1)
    print("t4 = ", t4)


# ===============================  exmaple 8 ===============================
# 通过torch.logspace创建对数均分数列张量
# flag = True
flag = False
if flag:
    t1 = torch.logspace(-10, 10, steps=5)
    print("t1 = ", t1)
    t2 = torch.logspace(0.1, 1, steps=5)
    print("t2 = ", t2)
    t3 = torch.logspace(0.1, 1, steps=1)
    print("t3 = ", t3)
    t4 = torch.logspace(2, 2, steps=1, base=2)
    print("t4 = ", t4)


# ===============================  exmaple 9 ===============================
# 通过torch.eye创建单位对角矩阵(2维张量),默认为方阵
# flag = True
flag = False
if flag:
    t1 = torch.eye(3)
    print("t1 = ", t1)
    t2 = torch.eye(2, 3)
    print("t2 = ", t2)
    t3 = torch.eye(3, 2)
    print("t3 = ", t3)


# ===============================  exmaple 10 ===============================
# 通过torch.normal创建正态分布张量
# flag = True
flag = False
if flag:
    # mean:标量 std: 标量, 这里需要设置 size
    t1 = torch.normal(2, 3, size=(1, 4))
    print("t1 = ", t1)

    # mean 为标量,std 为张量
    mean = 0.5
    std = torch.arange(1, 6, dtype=torch.float)
    t2 = torch.normal(mean, std)
    print("mean:{}nstd:{}".format(mean, std))
    print("t2 = ", t2)

    # mean 为张量,std 为标量
    mean = torch.arange(1, 6, dtype=torch.float)
    std = 1
    t3 = torch.normal(mean, std)
    print("mean:{}nstd:{}".format(mean, std))
    print("t3 = ", t3)

    # mean 为张量,std 为张量
    mean = torch.arange(1, 6, dtype=torch.float)
    std = torch.arange(1, 6, dtype=torch.float)
    t4 = torch.normal(mean, std)
    print("mean:{}nstd:{}".format(mean, std))
    print("t4 = ", t4)


# ===============================  exmaple 11 ===============================
# 通过torch.randn和torch.randn_like创建标准正态分布
# flag = True
flag = False
if flag:
    t1 = torch.randn(4)
    print("t1 = ", t1)
    t2 = torch.randn(2, 3)
    print("t2 = ", t2)
    input = torch.tensor(np.ones((3, 3)))
    t3 = torch.randn_like(input)
    print("t3 = ", t3)


# ===============================  exmaple 12 ===============================
# 通过torch.rand和torch.rand_like创建由区间[0,1)上均匀分布的随机数填充的张量
# flag = True
flag = False
if flag:
    t1 = torch.rand(4)
    print("t1 = ", t1)
    t2 = torch.rand(2, 3)
    print("t2 = ", t2)
    input = torch.tensor(np.ones((3, 3)))
    t3 = torch.rand_like(input)
    print("t3 = ", t3)


# ===============================  exmaple 13 ===============================
# 通过torch.randint和torch.randint_like创建由在[low,high)之间均匀生成的随机整数填充的张量
# flag = True
flag = False
if flag:
    t1 = torch.randint(3, 5, (3, ))
    print("t1 = ", t1)
    t2 = torch.randint(10, (2, 2))
    print("t2 = ", t2)
    input = torch.tensor(np.ones((3, 3)))
    t3 = torch.randint_like(input, 1, 10)
    print("t3 = ", t3)


# ===============================  exmaple 14 ===============================
# 通过torch.randperm创建从0到n-1的整数的随机排列
# flag = True
flag = False
if flag:
    t1 = torch.randperm(4)
    print("t1 = ", t1)
    t2 = torch.randperm(10)
    print("t2 = ", t2)


# ===============================  exmaple 15 ===============================
# 通过torch.bernoulli生成伯努利分布
flag = True
# flag = False
if flag:
    a = torch.empty(3, 3).uniform_(0, 1)
    print("a = ", a)
    t1 = torch.bernoulli(a)
    print("t1 = ", t1)

    a = torch.ones(3, 3)
    print("a = ", a)
    t2 = torch.bernoulli(a)
    print("t2 = ", t2)

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>