Python NLP 基础常见code 技巧

向量相关:

1.根据步长创建一维tensor的几个方法

pytorch每日一学20(torch.arange()、torch.range()、torch.linespace()、torch.logspace())根据步长创造一维tensor_Fluid_ray的博客-CSDN博客_torch。arange

pytorch.range() 和 pytorch.arange() 的区别_Who is abc的博客-CSDN博客_torch.arrange 

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

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

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

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

参数解释:

start:创建的tensor元素的起始值(不一定一定第一个元素就是start),默认为0。
end:创建tensor中元素的末尾值(不一定最后一个值一定取到end,得看具体哪个方法和值)
step:指定从开始到结尾取数时每次增加多少,默认为1.
out:表明创建后tensor赋予哪个变量。
dtype:指定tensor中数据元素的类型,如果为None,取默认值,默认值可由torch.set_default_tensor_type()来改变,以前讲过这个方法。
layout:返回tensor的布局,默认为torch.strided。
device:生成tensor所处的设备,可以为cpu或者cuda。
requires_grad:指定返回tensor需不需要梯度,默认为False。

重要区别:

  1. torch.range(start=1, end=6) 的结果是会包含end的,
    torch.arange(start=1, end=6)的结果并不包含end
  2. 两者创建的tensor的类型也不一样。 

2.数据维度缩放 

PyTorch学习笔记——常用函数总结(一)のtorch.squeeze()和Tensor常见创建方法_Yale曼陀罗的博客-CSDN博客_torch计算向量模长

(1) torch.squeeze(input, dim=None, out=None) 

这个函数主要对数据的维度进行压缩去掉维数为1的的维度。比如:是一行或者一列这种,一个一行三列(1,3)的数去掉第一个维数为一的维度之后就变成(3)行。b=torch.squeeze(a,N) 就是将a中所有为1的维度删掉,不为1的维度没有影响。

参数说明:

input (Tensor):

输入张量(the input tensor.)


dim (int, optional):

将输入Tensor的第dim个维度位置进行压缩,如果输入Tensor此处维度为1则压缩成功,否则失败。如果该参数给定,

则输入张量将仅在该维度上压缩(if given, the input will be squeezed only in this dimension.),如果该参数不给定,则默认将输入Tensor所有维度为1的进行压缩。

参数dim的取值范围为:[-input.dim(), input.dim()-1] 。

(2) torch.unsqueeze(input, dim)函数详解:

在tensor的某个维度上添加一个维数为1的维度,这个功能用view()函数也可以实现。

比如:原本有个三行的数据(3),在0的位置加了一维就变成一行三列(1,3)。

a.unsqueeze(N) 就是在a中指定位置N加上一个维数为1的维度。

还有一种形式就是b=torch.unsqueeze(a,N) a就是在a中指定位置N加上一个维数为1的维度。

这一功能尤其在神经网络输入单个样本时很有用,由于pytorch神经网络要求的输入都是mini-batch型的,维度为[batch_size, channels, w, h],而一个样本的维度为[c, w, h],此时用unsqueeze()增加一个维度变为[1, c, w, h]就很方便了。

参数说明:

input (Tensor):输入张量(the input tensor.)
dim (int):插入维数为一的维度的位置(the index at which to insert the singleton dimension.)参数dim的取值范围为:[-input.dim() - 1, input.dim() + 1)
 

函数创建相关:

  1. 参数&关键字参数kward argument

[python]4.7.2. Keyword Arguments_竹二木的博客-CSDN博客 

你可能感兴趣的:(NLP,文本分析,python,python,自然语言处理)