Tensor的创建方法

目录


1、直接创建Tensor——torch.tensor()

torch.tensor(data,dtype=None,device=None,requires_grad=False,pin_memory=False)
  • data:数据,可以是list,numpy
  • dtype:数据类型,默认与data的一致
  • device:张量所在的设备(cuda或者cpu)
  • requires_grad:是否需要梯度
  • pin_memory:是否存于锁存内存

pin_memory就是锁页内存,创建DataLoader时,设置pin_memory=True,则意味着生成的Tensor数据最开始是属于内存中的锁页内存,这样将内存的Tensor转义到GPU的显存就会更快一些。

例子:

import numpy as np
import torch
arr = np.ones((3, 3))
print("ndarray的数据类型:", arr.dtype)
t= torch.tensor(arr)
print(t)

 运行后的结果为:

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

若要创建一个放在GPU中的数据,则可以写成:

import numpy as np
import torch
device= torch.device("cuda" if torch.cuda.is_available() else 'cpu')
arr = np.ones((3, 3))
print("ndarray的数据类型:", arr.dtype)
t = torch.tensor(arr, device=device)
print(t)

最后运行的结果与上面一致。

2、从numpy创建tensor——torch.from_numpy(ndarray)

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

例子:

import numpy as np
import torch
arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)
# 修改 tensor,array 也会被修改
print("\n修改tensor")
t[0, 0] = -1
print("numpy array: ", arr)
print("tensor : ", t)

运行后的结果为:

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

3、根据数值创建tensor

(1)torch.zeros():根据size创建全0张量

torch.zeros(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • size:张量的形状
  • out:输出的张量,如果指定了 out,那么torch.zeros()返回的张量和 out 指向的是同一个地址
  • layout:内存中的布局形式,有 strided,sparse_coo 等。当是稀疏矩阵时,设置为sparse_coo 可以减少内存占用
  • device:张量所在的设备,cuda/cpu
  • requires_grad:是否需要梯度

例子:

import torch
out_t = torch.tensor([1])
print(f"out_t:{out_t}")
# 这里制定了 out
t = torch.zeros((3, 3), out=out_t)
print(t, '\n', out_t)
# id 是取内存地址。最终 t 和 out_t 是同一个内存地址
print(id(t), id(out_t), id(t) == id(out_t))

运行后得到的结果为:

out_t:tensor([1])
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2364007186320 2364007186320 True

由上可见,最终t和out_t共享一个内存地址。

(2)torch.zeros_like:跟根据input形状创建全0的张量

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

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

(3)torch.full(),torch.full_like():创建自定义某一数值的张量

torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • size: 张量的形状,如 (3,3)

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

例子:

import torch
t = torch.full((3, 3), 8)
print(t)

运行后的结果为:

tensor([[8, 8, 8],
        [8, 8, 8],
        [8, 8, 8]])

(4)torch.arange():创建等差的一维张量

⭐注意区间为:[start,end)。

torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • start: 数列起始值,默认为0

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

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

例子:

import torch
t = torch.arange(2, 10, 2)
print(t)

运行后的结果为:

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

(5)torch.linspace():创建均分的一维张量

⭐注意区间为:[start,end]。

torch.linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • steps: 数列长度 (元素个数)

例子:

import torch
t = torch.linspace(2, 10, 3)
print(t)

运行后的结果为:

tensor([ 2.,  6., 10.])

(6)torch.logspace():创建对数均分的一维张量

⭐注意区间为:[start,end]。

  • steps: 数列长度 (元素个数)

  • base: 对数函数的底,默认为 10

例子:

import torch
t = torch.logspace(2, 4, 3)
print(t)

运行后的结果为:

tensor([  100.,  1000., 10000.])

(7)torch.eye():创建单位对角矩阵(2维张量)

⭐默认输出的为方阵。

torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • n: 矩阵行数。通常只设置 n,为方阵

  • m: 矩阵列数

例子:

import torch
t = torch.eye(3)
h = torch.eye(3,4)
print(f"t:{t}")
print(f"h:{h}")

运行后的结果为:

t:tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
h:tensor([[1., 0., 0., 0.],
        [0., 1., 0., 0.],
        [0., 0., 1., 0.]])

3、根据概率创建Tensor

(1)torch.mormal():生成正态分布(高斯分布)

⭐返回一个张量,包含从给定参数means,std的离散正态分布中抽取随机数。

torch.normal(mean, std, *, generator=None, out=None)
  • mean: 均值

  • std: 标准差

有4种模式:


a. mean 为标量,std 为标量

此时需要设置size

例子:

import torch
t_normal = torch.normal(0., 1., size=(4,))
print(f"t_normal:{t_normal}")

运行后的结果为:

t_normal:tensor([ 0.7098,  1.5432, -0.1568, -0.6350])

b. mean为标量,std为张量

c. mean为张量,std为标量

例子:

import torch
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:tensor([1., 2., 3., 4.])
std:1
tensor([2.0187, 1.2123, 4.8712, 1.6091])

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

d. 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:tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([0.7926, 1.2278, 4.6788, 5.8131])

其中 0.7926 是从正态分布N(1,1)中采样得到的,1.2278是从正态分布N(2,2)中采样得到的,其他数字以此类推。

(2)torch.rand() 和 torch.rand_like():在区间 [0, 1) 上生成均匀分布

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

(3)torch.randint() 和 torch.randint_like():在区间 [low, high) 上生成整数均匀分布

torch.randint(low=0, high, size, *, generator=None, out=None,
dtype=None, layout=torch.strided, device=None, requires_grad=False)

(4)torch.randperm():生成从 0 到 n-1 的随机排列

torch.randperm(n, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False)

⭐常用于生成索引

  • n: 张量的长度

(5)torch.bernoulli():以 input 为概率,生成伯努利分布 (0-1 分布,两点分布)

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

参考链接:[PyTorch 学习笔记] 1.2 Tensor(张量)介绍

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月7日 上午11:31
下一篇 2023年3月7日 下午10:13

相关推荐