pytorch Tensor类

创建tensor

FloatTensor(float32),IntTensor(int32),Tensor,longtensor(float64)

shape创建

print(
     torch.FloatTensor(2, 3),'\n',
     torch.IntTensor(2, 3),'\n',
     torch.Tensor(2, 3),'\n',
)

tensor([[4.9556e+28, 1.7485e+25, 2.0022e-19],
        [7.3909e+22, 1.3556e-19, 3.0097e+29]]) 
 tensor([[-318699984,      32620, -282333072],
        [     32620, -283229904,      32620]], dtype=torch.int32) 
 tensor([[-5.3960e+28,  4.5710e-41, -5.2479e+28],
        [ 4.5710e-41, -8.5950e+27,  4.5710e-41]]) 

 可以看到都是shape为(2,3)的tensor,使用小写的tensor会报错。

list创建

import torch
import numpy as np

a = np.array([2, 3.3])


print(
    torch.FloatTensor([2, 3.3]),
    torch.Tensor([2, 3.3])
)

tensor([2.0000, 3.3000]) tensor([2.0000, 3.3000]) tensor([2.0000, 3.3000])

numpy创建

import torch
import numpy as np

a = np.array([2, 3.3])


print(
     torch.FloatTensor(a),'\n',
     torch.IntTensor(a),'\n',
     torch.Tensor(a),'\n',
     torch.from_numpy(window_size)
)

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

torch.tensor

可使用numpy或list初始化,但不能用shape,可以指定device,dtype等等

a = np.array([2, 3.3])


print(
     torch.tensor(a,dtype=torch.int32),'\n',
     torch.tensor(a,device='cuda:0'),'\n',
)

tensor([2, 3], dtype=torch.int32) 
 tensor([2.0000, 3.3000], device='cuda:0', dtype=torch.float64) 

小结:可以看到还是FloatTensor,IntTensor ,Tensor这种大写的比较方便,传入列表,传入numpy数组都能得到值,并且还可以用于指定shape,用小写tensor也挺好,指定形式比较方便。

大写的FloatTensor这种实际上就是调用了torch.FloatTensor的构造器。

因为是调用了类的构造器创建tensor,所以我们想创建cuda的tensor就直接用cuda的tensor

类的构造器,比如torch.cuda.FloatTensor() ,那么就能直接创建在默认设备上的构造器。

生成与一个tensor类型和Device一模一样的tensor

Tensor.new_tensor(data*dtype=Nonedevice=Nonerequires_grad=Falselayout=torch.stridedpin_memory=False) → Tensor

Returns a new Tensor with data as the tensor data. By default, the returned Tensor has the same torch.dtype and torch.device as this tensor.

将数组转成和Tensor,data不同,但torch.dtype和torch.device默认和该Tensor相同

Tensor.new_empty(size*dtype=Nonedevice=Nonerequires_grad=Falselayout=torch.stridedpin_memory=False) → Tensor

>>> tensor = torch.ones(())
>>> tensor.new_empty((2, 3))
tensor([[ 5.8182e-18,  4.5765e-41, -1.0545e+30],
        [ 3.0949e-41,  4.4842e-44,  0.0000e+00]])

不同之处在于new_tensor传入的是data,new_empty传入的是size

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

Parameters:

size (int...) – a list, tuple, or torch.Size of integers defining the shape of the output tensor.

返回一个大小size为 的张量0。默认情况下,返回的张量与此张量具有相同的torch.dtype和 torch.device。

生成随机的tensor

教程

PyTorch 常用方法总结1:生成随机数Tensor的方法汇总(标准分布、正态分布……) - 知乎

主要使用的是

里面的sizes (int...) - 整数序列,定义了输出张量的形状

torch.rand(*sizes, out=None) → Tensor

[0, 1)的均匀分布中抽取的一组随机数

torch.randn(*sizes, out=None) → Tensor

标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数。

torch.normal(meanstd*generator=Noneout=None) → Tensor

从指定均值means和标准差std的离散正态分布中抽取的一组随机数。

注意:

  •  1个元素对应1个正态分布的输出!!

  • mean可以为tensor或 float,
  • 如果是一个张量,则每个值表明对应输出元素的所属正态分布均值
  • 如果是数,则是所有分布的均值都为他

  • 同理,std是一个张量,是每个输出元素的正态分布的标准差
  • 如果是一个张量,则每个值表明对应输出元素的所属正态分布标准差
  • 如果是数,则是所有分布的标准差都为他

  • mean和的形状std不需要匹配,但每个张量中的元素总数需要相同。

std是 CUDA 张量时,此函数将其设备与 CPU 同步。

tensor的size的指定

如果双方都为tensor:当形状不匹配时,使用的形状mean 作为返回输出张量的形状

如果一方为tensor,另一方为float:输出size取决于输入为tensor的size

如果都为float,则需要手动指定size,也就是再传入一个size参数

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

生成0或1

伯努利分布公式:

 也就是某个点有p的概率为1,有(1-p)的概率为0。

input (Tensor) – the input tensor of probability values for the Bernoulli distribution

还是老样子,一个数对应了1个伯努利分布的输出,也就是一个分布输出一个数。

返回tensor :返回tensor的值只能为0或1且与input有相同的size。

示例:

>>> a = torch.empty(3, 3).uniform_(0, 1)  # generate a uniform random matrix with range [0, 1]
>>> a
tensor([[ 0.1737,  0.0950,  0.3609],
        [ 0.7148,  0.0289,  0.2676],
        [ 0.9456,  0.8937,  0.7202]])
>>> torch.bernoulli(a)
tensor([[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 1.,  1.,  1.]])

>>> a = torch.ones(3, 3) # probability of drawing "1" is 1
>>> torch.bernoulli(a)
tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
>>> a = torch.zeros(3, 3) # probability of drawing "1" is 0
>>> torch.bernoulli(a)
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])

总结:可以看到使用分布生成数据的,如果有分布的参数可以调(比如torch.normal的mean和std,伯努利的p),那么这种都是要求输入tensor作为参数的,每一个分布独立输出一个结果,输出当然也就和输入tensor一致

生成顺序的tensor

torch.arange(start=0endstep=1*out=Nonedtype=Nonelayout=torch.strideddevice=Nonerequires_grad=False) → Tensor

包括start,不包括end,初始out=start

outi+1​=outi​+step

通常用法,就是只指定end,生成0~end-1的数组

>>> torch.arange(5)
tensor([ 0,  1,  2,  3,  4])
>>> torch.arange(1, 4)
tensor([ 1,  2,  3])
>>> torch.arange(1, 2.5, 0.5)
tensor([ 1.0000,  1.5000,  2.0000])

torch.linspace(startendsteps*out=Nonedtype=Nonelayout=torch.strideddevice=Nonerequires_grad=False) → Tensor

生成step个差值相等数据,包括start和end,公式如上

数据种类dtype

Data type

dtype

CPU tensor

GPU tensor

32-bit floating point

torch.float32 or torch.float

torch.FloatTensor

torch.cuda.FloatTensor

64-bit floating point

torch.float64 or torch.double

torch.DoubleTensor

torch.cuda.DoubleTensor

16-bit floating point [1]

torch.float16 or torch.half

torch.HalfTensor

torch.cuda.HalfTensor

16-bit floating point [2]

torch.bfloat16

torch.BFloat16Tensor

torch.cuda.BFloat16Tensor

8-bit integer (unsigned)

torch.uint8

torch.ByteTensor

torch.cuda.ByteTensor

8-bit integer (signed)

torch.int8

torch.CharTensor

torch.cuda.CharTensor

16-bit integer (signed)

torch.int16 or torch.short

torch.ShortTensor

torch.cuda.ShortTensor

32-bit integer (signed)

torch.int32 or torch.int

torch.IntTensor

torch.cuda.IntTensor

64-bit integer (signed)

torch.int64 or torch.long

torch.LongTensor

torch.cuda.LongTensor

Boolean

torch.bool

torch.BoolTensor

torch.cuda.BoolTensor

在数组有浮点数时会默认生成float64的ndarray,在数组全是整数时torch.int64为默认值

在深度学习中通常用float32和int64

改变tensor类型

  1. 使用tensor.type()函数;
  2. 使用type_as(tesnor)将张量转换为给定类型的张量。
  3. 使用构造器

1.2是等价的,调用的是一个接口,注意这里只改变dtype,不同于new_tensor和new_shape

1.tensor.type()

type(new_type=None, async=False)
import torch

tensor = torch.randn(3, 5)
print(tensor)

int_tensor = tensor.type(torch.IntTensor)
print(int_tensor)

-0.4449  0.0332  0.5187  0.1271  2.2303
 1.3961 -0.1542  0.8498 -0.3438 -0.2834
-0.5554  0.1684  1.5216  2.4527  0.0379
[torch.FloatTensor of size 3x5]


 0  0  0  0  2
 1  0  0  0  0
 0  0  1  2  0
[torch.IntTensor of size 3x5]

2.直接使用FloatTensor,IntTensor,Tensor来重新构造

3.Tensor.type_as(tensor) → Tensor

使用type_as(tesnor)将张量转换为给定tensor类型的张量。


tensor1=tensor1.type_as(tensor2)

4.tensor.int(),tensor.float

Tensor对象其他成员和方法

device参数

可以查看属于哪个设备

.cuda()和to()

转换设备,具体看

pytorch cuda 数据转换到gpu_wa1ttinG的博客-CSDN博客


 

requires_grad,grad_fn,grad

参考

requires_grad,grad_fn,grad的含义及使用_dlage的博客-CSDN博客

requires_grad: 如果需要为张量计算梯度,则为True,否则为False。我们使用pytorch创建tensor时,可以指定requires_grad为True(默认为False),

grad_fn: grad_fn用来记录变量是怎么来的,方便计算梯度,y = x*3,grad_fn记录了y由x计算的过程。

grad:当执行完了backward()之后,通过x.grad查看x的梯度值。
 

注:在requires_grad为ture时,grad_fn,grad才会生效

tensor.data

如果在tensor的requires_grad为true的情况下,我们想要其不含计算图,梯度等等的

l1=torch.tensor([1],requires_grad=True,dtype=torch.float32)
print(l1)

tensor([1.], requires_grad=True)

l1=torch.tensor([1],requires_grad=True,dtype=torch.float32)
print(l1.data)

tensor([1.])

item()

只有一个元素时,调用,可以直接返回基本数据类型,比如int,float等等

注意点

  • tensor对象的方法绝大多数比如new_empty,new_zero,cumsu,cuda()和to(),tensor.type(),tensor.as()等等,都是新生成对象。极少数直接对tensor本身进行操作,比如zero_(),这种后面带_的是直接进行操作的

猜你喜欢

转载自blog.csdn.net/zxyOVO/article/details/129971131